Listview + BaseAdapter - how to notify about a change in one element?

I have a list view filed by BaseAdapter.

When something changes in the data, I call BaseAdapter.notifyDataSetChanged. Everything is working fine.

Now it’s interesting, if I change some small details in some element of the list, is there an optimized way to update the presentation of an individual element if it is displayed on the screen ? I believe that notifyDataSetChanged blindly rearranges the views of all visible elements in the list, which is not optimal if there is a trivial change to the element.

+4
source share
2 answers

Yes, there is a way. Assuming that I can identify the list item, for example, assigning View.setTag to some value, I can iterate over the list items and, if desired, reinstall only one list item or even update only some sub-views of the item.

This is simple and relatively cheap (linear search):

for(int i = list.getChildCount(); --i>=0; ){ View v = list.getChildAt(i); Object id = v.getTag(); if(id==myId){ updateListItem(id, v); break; } } 

where myId is some identifier of the item I want to update, and updateListItem makes the desired changes to the list item. Proven and works great and very effective.

0
source

No, I think this is not possible if you do not implement your own ListView class extension. Here is the source code for setAdapter() .

You will see that the ListView only registers as an observer using mAdapter.registerDataSetObserver(mDataSetObserver); And DataSetObserver does not provide any notification of a change in a specific position.

However, it may not be necessary to notify you of updates to certain items, because as far as I know, ListView only renders and updates items that are currently visible on the screen, so there is no need for optimization.

+1
source

Source: https://habr.com/ru/post/1381295/


All Articles