2

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;
    }
Meet
  • 164
  • 2
  • 11

1 Answers1

2

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.

Gennadii Saprykin
  • 4,505
  • 8
  • 31
  • 41
  • When list view appeared on a screen, there are no items yet, so it goes to **if** for every item that has to be created. Then, when you start scrolling, it tries to reuse those views that become invisible once you scroll. So usually, it goes to **else** for showing the following items because the previous items can be reused. This is the case for simple scenario when all items in a list use the same layout, i.e. only the content is different. – Gennadii Saprykin Jun 27 '18 at 11:30
  • 1
    thanks brother now i am understand very well . @Gennadii – Meet Jun 27 '18 at 11:32
  • you're welcome! Please accept the answer if that answers your question. Good luck! :) – Gennadii Saprykin Jun 27 '18 at 11:33