1

I have a List View and every item has pin button, that start service (downloading item). Service send percents via broadcast, and I have to update pin button. I'm trying to do it with getting view from List View and set value to pin button such as

int firstVisibleElement = postListView.getFirstVisiblePosition();
int lastVisibleElement = postListView.getLastVisiblePosition();
if (position >= firstVisibleElement && position <= lastVisibleElement) {
     View view = postListView.getChildAt(lastVisibleElement - position);
    }

But when I scroll during sync, it return wrong view. How can I fix it?

streamride
  • 567
  • 4
  • 16
  • [This might be the same problem](http://stackoverflow.com/questions/17953268/hide-custom-search-bar-if-all-items-in-adapter-are-showing) – codeMagic Jan 23 '14 at 14:06

1 Answers1

0

The "conversion" from dataset position and "child view position" in ListView is wrong.

The children views in ListView are numbered from 0 to listView.getChildCount() - 1. A position in the dataset, as the variable position should be, goes from 0 to adapter.getCount() - 1. The method listview.getFirstVisiblePosition() returns the first dataset position that is visible on the screen, i.e. what dataset position corresponds to the 0th view in ListView.

Now say you have 15 items in your Adapter, you have 10 items in your ListView on screen, and you scrolled down by 2 items. This means the visible item positions in the dataset are from 2 to 11, but the "child view positions" are always from 0 to 9. listview.getFirstVisiblePosition() would return 2.

By mean of this example, it's easy to convert from "dataset position" to "child view position": the child view position is basically the dataset position minus the first visible dataset position:

int firstVisibleElement = postListView.getFirstVisiblePosition();
int lastVisibleElement = postListView.getLastVisiblePosition();
if (position >= firstVisibleElement && position <= lastVisibleElement) {
    View view = postListView.getChildAt(position - firstVisibleElement);
}
Gil Vegliach
  • 3,542
  • 2
  • 25
  • 37