@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = ContactViewActivity.this.getLayoutInflater().inflate(R.layout.contact_view_field_row,
parent, false);
}
String value = (String)getItem(position);
TextView fieldValue = (TextView)convertView.findViewById(R.id.contact_view_row_value);
fieldValue.setText(value);
return convertView;
}
The above code is taken from a BaseAdapter class. So what is the point of setting the inflated view to convertView? The whole point of the getView is to make a view if there isn't one, give it attributes, then return it so it can be shown in the application in the ListView right? So why not just say findViewById(R.id.contact_view_row_value);? I mean what are we really doing with the layoutInflater? I'd think that since we set it equal to convertView, there would be no need to type convertView.findViewById. I mean it is already equal to an inflated XML file right? I'm quite confused here, I'd really appreciate some clarification.
Because
convertView
is something that can be reused, though at runtime you don't know whether you're being provided an existingView
whose data must be updated, or if a newView
needs to be inflated.When your application starts, you need to
inflate
yourViews
in order for any data to be displayed in yourListView
at all. Inflate means to parse the resource XML into a graphical object that and provide it with Android'sContext
, so it becomes something that has the potential to be rendered and interacted with on the graphical hierarchy. Later on in the application, Android tries to help you save resources and avoid unnecessary inflation by passing you aView
that had been inflated earlier; that's why we check ifconvertView
is not equal tonull
. If it's not, you can convert that existingView
into something that displays data relevant for the current index.However, it's worth noting that the
ListView
is now deprecated. Try using theRecyclerView
instead, where this behaviour is a little more obvious. Here's an example.