I can't understand what is a convert view.. Specifically, when does the program enter if condition and when else condition?
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.data, parent, false);
holder = new ViewHolder();
holder.txtDesc = convertView.findViewById(R.id.txtDesc);
holder.txtSubject = convertView.findViewById(R.id.txtSubject);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtDesc.setText(profileListView.get(position).getName());
holder.txtSubject.setText(profileListView.get(position).getEmail());
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, profileListView.get(position).getName()+"hi go to detail page", Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
The convertView
is a view that is reused by ListView
adapter. When you scroll, items that are no longer visible become reused for showing new items that become visible. This is called recycling and it's done for performance improvements.
When convertView
is null it means there is no view that can be reused for this items, so you have to inflate a new one from an XML layout and return it at the end of the method.
When it is not null, it means the view has been reused. You can take the convert view, replace old data with the new one, and return this view instead. This way you can eliminate the inflate
method call which is an expensive operation. This helps your list view to scroll smoothly.
There is also another performance improvement here - the view holder pattern. It stores references to item views, so that you don't have to call findViewById
operation for every item. This is also an expensive operation which is nice to be avoided.