Home » Android » android – How to get the view of a ListView item?

android – How to get the view of a ListView item?

Posted by: admin June 15, 2020 Leave a comment


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?

How to&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().


int position = 0;
listview.setItemChecked(position, true);
View wantedView = adapter.getView(position, null, listview);


Here is what i did

private View oldSelection;

public void onItemClick(AdapterView<?> arg0, View view, int position,
        long arg3) {

    public void highlightSelectdListItem(int position) {
    View newsItemView = mGridVIew.getChildAt(position);
    oldSelection = newsItemView;

public void clearPreviousSelection() {
    if (oldSelection != null) {