简体   繁体   中英

Android How to update single row in listview?

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?

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, ie 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM