I have a simple ListView in my app. The ListView is binded to my ArrayAdapter class with a getView
method implemented as follows.
class ScheduleListAdapter extends ArrayAdapter<ScheduleItem>
{
@Override public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = _activity.getLayoutInflater().inflate(R.layout.schedule_item2, null);
}
// not shown - code initialize elements of view
return view;
}
In the above code, notice that the parent
ViewGroup parameter is ignored and not passed to the inflate
call. I modeled this code after several books and online examples.
But now I've seen other examples on the web suggest that parent
needs to be passed to inflate
as follows:
View view = inflater.inflate(R.layout.schedule_item2, parent, false);
I've tried it both ways and it seems to work fine either way. But looking at the source for inflate, it seems that when the parent
is passed, it can influence the LayoutParams that are used initialize to the view. But I'm uncertain how to interpret the code beyond this.
It gets confusing when you compare the above to other online examples of using LayoutInflater with Fragments and RecyclerView. Those examples always seem to explicitly pass the parent
parameter to inflate
. I'm assuming there are situations where it makes sense to do this.
Can someone explain when to pass ViewGroup parent
to inflate
and when not to?
As a result, without any known parent, all LayoutParams you declared on the root element of your XML tree will just get thrown away. Without LayoutParams, the ViewGroup that eventually hosts the inflated layout is left to generate a default set for you. If you are lucky (and in many cases you are) these default parameters are the same as what you had in XML