Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the view of a ListView item?

I have two ListViews (A and B) with items of the same type (a class I created)

When I click on an item from A, it adds this object on B and if I click again it removes it. Only that when an item is selected, I change its background using view.setBackgroundColor(myColor).

I want to be able to remove the item from list B (it works), but I want also to reset the background color. I can't figure out how to get the view of this item I'm removing.

Any ideas?

like image 714
Lucas Avatar asked Mar 25 '11 13:03

Lucas


2 Answers

There's no guarantee that any specific ListView item will even have a view at any given time. If the item is currently off-screen, then it may not have a view. Since a specific item might not have a view, it might not make any sense to try to get the item's view.

Beyond that, because of the way ListView creates and reuses views, you'll see some odd, undesirable effects if you simply modify the views directly. As the user scrolls through the list, items that become visible will incorrectly end up with the same backgrounds as other items that have fallen outside the visible portion.

I don't know whether what follows is the best way to implement your functionality because I don't know the cost of rebuilding the list after a change. Here's the (probably naive) way I would do this:

  1. Add another boolean member to your data object, something like isInSecondList.
  2. Override getView() in the Adapter. In getView(), set the background to either normal or highlighted depending on the the value of the item's isInSecondList.
  3. When an item is added or removed from the second list, update the data object to reflect the change, then call the Adapter's notifyDataSetChanged().
like image 97
erichamion Avatar answered Sep 22 '22 02:09

erichamion


int position = 0;
listview.setItemChecked(position, true);
View wantedView = adapter.getView(position, null, listview);
like image 25
ngocquynh_183 Avatar answered Sep 24 '22 02:09

ngocquynh_183