Is passing in the LayoutInflater necessary?


#1

I just wanted to make sure I understand the reasons behind decisions so I can become a better programmer.

The book has us add a LayoutInflater parameter in our CrimeHolder constructor, and then we make a LayoutInflater in our CrimeAdapter and pass it in.

In CrimeHolder:

    private CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
       super(inflater.inflate(R.layout.list_item_crime, parent, false));
    }

In CrimeAdapter:

    public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
       return new CrimeHolder(layoutInflater, parent);
   }

But would there be anything wrong with just getting the inflater inside of the CrimeHolder constructor instead?
Would this be considered unsafe or bad practice for any reason? It seems like slightly less complexity.

In CrimeHolder:

    private CrimeHolder(ViewGroup parent) {
       super(LayoutInflater.from(getActivity()).inflate(R.layout.list_item_crime, parent, false));
    }

In CrimeAdapter:

    public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       return new CrimeHolder(parent);
   }

Thanks!


#2

The reason we didn’t use your second example is because there is just so much code in that super call that it’s hard to read.

Even in the way that we did it, I’m not happy with how much code is in that super call. We wanted to have the CrimeHolder be the only class that knows about and cares about that particular layout file, so we ended up with what you see in the book.