LuxuryMode LuxuryMode - 1 year ago 90
Android Question

ListView reusing views when ... I don't want it to

I've got a

, each of
of which contains a
. After I toggle it and then scroll up or down, the ListView is recycling the Views and so some of the others are mirroring the checked state of the
. I don't want this. How can I prevent it?

Answer Source

Android recycles list items for performance purposes. It is highly recommended to reuse them if you want your ListView to scroll smoothly.

For each list item the getView function of your adapter is called. There, is where you have to assign the values for the item the ListView is asking for.

Have a look at this example:

public View getView(int position, View convertView, ViewGroup parent)
    ViewHolder holder = null;

    if ( convertView == null )
        /* There is no view at this position, we create a new one. 
           In this case by inflating an xml layout */
        convertView = mInflater.inflate(R.layout.listview_item, null);  
        holder = new ViewHolder();
        holder.toggleOk = (ToggleButton) convertView.findViewById( );
        convertView.setTag (holder);
        /* We recycle a View that already exists */
        holder = (ViewHolder) convertView.getTag ();

    // Once we have a reference to the View we are returning, we set its values.

    // Here is where you should set the ToggleButton value for this item!!!

    holder.toggleOk.setChecked( mToggles.get( position ) );

    return convertView;

Notice that ViewHolder is a static class we use to recycle that view. Its properties are the views your list item has. It is declared in your adapter.

static class ViewHolder{
    ToggleButton toggleOk;

mToggles is declared as a private property in your adapter and set with a public method like this:

public void setToggleList( ArrayList<Boolean> list ){
        this.mToggles = list;

Have a look at other custom ListView examples for more information.

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download