How to get a view of a ListView?

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

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

I want to remove an item from list B (it works), but I also want to reset the background color. I cannot figure out how to get an idea of ​​this element that I am removing.

Any ideas?

+8
android listview
source share
3 answers

There is no guarantee that any particular ListView will even have a view at any given time. If an item is currently off screen, it may not have a view. Since a particular element may not have a representation, it may not make sense to try to get a representation of the element.

In addition, due to the way the ListView creates and reuses views, you will see some odd unwanted effects if you just change the views directly. As the user scrolls through the list, the elements that become visible will incorrectly coincide with the same background as other elements that fall outside the visible part.

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

  • Add another logical element to your data object, something like isInSecondList .
  • Replace getView() in the adapter. In getView() set the background to both normal and highlighted depending on the value of the isInSecondList element.
  • When an item is added or removed from the second list, update the data object to reflect the change, then call the adapter notifyDataSetChanged() .
+10
source share
 int position = 0; listview.setItemChecked(position, true); View wantedView = adapter.getView(position, null, listview); 
+5
source share

Here is what i did

 private View oldSelection; @Override public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) { highlightSelectdListItem(position); } public void highlightSelectdListItem(int position) { clearPreviousSelection(); View newsItemView = mGridVIew.getChildAt(position); oldSelection = newsItemView; newsItemView.setBackgroundColor(Color.GRAY); } public void clearPreviousSelection() { if (oldSelection != null) { oldSelection.setBackgroundColor(Color.TRANSPARENT); } } 
0
source share

All Articles