1

I have a listView and want to expand each item when you press it. I have the following code to do so. I works by inflating a ViewStub.

It works fine. That is, when I press a list item it does indeed inflate. So far so good.

However, my list is long, and I noticed that when I scroll down the list other items have inflated as well. I'm not entirely sure why. And when I scroll up again the item I originally press has "deflated" and some other item has become inflated instead.

@override
public void onListItemClick(ListView l, View v, int position, long id) {


    ListView list = getListView();
    int start = list.getFirstVisiblePosition();
    for (int i = start, j = list.getLastVisiblePosition(); i <= j; i++) {
        Cursor item = (Cursor) list.getItemAtPosition(i);

        if (id == item.getLong(item.getColumnIndex(ItemColumns._ID))) {
            View view = list.getChildAt(i - start);

            ViewStub stub = (ViewStub) view.findViewById(R.id.stub);
            if (stub != null) {
                stub.inflate();

            }       
        }
    }
}

Any help will be much appreciated!

Markus
  • 2,526
  • 4
  • 28
  • 35

1 Answers1

1

Android reuses views in a ListView. That is why there is a convertView in the getView(..) method of your Adapter. This SO post will explain: ListView reusing views when ... I don't want it to Basically what you need to do is hold a Set of items that are currently expanded, and in your getView(..) method do a lookup:

if(mExpanded.contains(getItem(position))) {
  //show expansion
} else {
  //hide expansion
}

then in your onListItemClick method you want to add the following:

if(!mExpanded.remove(getListView().getItem(position))) {
   mExpanded.add(getListView().getItem(position));
}

This will cause it to attempt remove the item, if the Set is not changed - that is the item wasn't in the Set to be removed then you want to add it...

Community
  • 1
  • 1
Salil Pandit
  • 1,498
  • 10
  • 13