Android ListView notifyDataSetChanged
I've got a custom listview, each entry contains spinning ProgressBar and single line textview. I'm always updating only the first item in the list开发者_开发百科. The problem is that every time I call notifyDataSetChanged all visible views are either recreated or recycled as convertView.
There are 2 problems with this approach:
all entries are recreated and that's slow - and that's not required as I'm updating only the textview in first entry
the ProgressBar animation restarts every time
So I though that I'll just keep the reference to first View in adapter and update it manually. It worked, but it randomly throws IllegalStateException ("The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread.")
How do I solve it? Is there a way to notify ListView that only first entry changed? Even if there is, ProgressBar animation will still fail. Is there any other way to update it manually?
Thanks
Whenever i need to update one single item on a listview i use this:
public void updateItemAt(int index) {
View v = listView.getChildAt(index - listView.getFirstVisiblePosition());
if (v != null) {
//updates the view
}
}
The downside is that you need to hold a reference to the listView in your adapter. As this code is usually called from a background task, you have to use a handler to call it:
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
int index = msg.what;
myAdapter.updateItemAt(index);
};
};
//when task is complete:
myHandler.sendEmptyMessage(index);
精彩评论