[Solved] How to implement OnClickListener of ListView items for good performance (avoiding slow scrolling)


It’s better to use a Wrapper to access to your View and to define your OnClickListener earlier (and outside the adapter for a better usability).

The following sample show how to handle 2 clickable View on one single item of the ListView with good performance:

public class ItemAdapter extends BaseAdapter {

    private List<Item> items;
    private ItemWrapper wrapper = null;
    private OnClickListener onMyItemClickListener1;
    private OnClickListener onMyItemClickListener2;

    public ItemAdapter(Context context, List<Item> items, OnClickListener onMyItemClickListener1, OnClickListener onMyItemClickListener2) {
        this.inflater = LayoutInflater.from(context);
        this.items = items;
        this.onMyItemClickListener1 = onMyItemClickListener1;
        this.onMyItemClickListener2 = onMyItemClickListener2;
    }        

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public synchronized View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;

        if (row == null) {
            row = inflater.inflate( R.layout.item, null);
            wrapper = new ItemWrapper(row);
            row.setTag(wrapper);
        } else {
            wrapper = (ItemWrapper)row.getTag();
        }

        Item item = getItem(position);
        wrapper.getClickView1().setOnClickListener(onMyItemClickListener1);
        wrapper.getClickView2().setOnClickListener(onMyItemClickListener2);
        return(row);
    }        
}

public class ItemWrapper {
    private View baseView;
    private View clickView1;
    private View clickView2;

    public ItemWrapper(View baseView) {
        this.baseView = baseView;
    } 

    public View getClickView1() {
        if ( clickView1 == null) {
            clickView1 = (View)baseView.findViewById(R.id.clickView1);
        }

        return(clickView1);
    }  

    public View getClickView2() {
        if ( clickView2 == null) {
            clickView2 = (View)baseView.findViewById(R.id.clickView2);
        }

        return(clickView2);
    }
}

2

solved How to implement OnClickListener of ListView items for good performance (avoiding slow scrolling)