Erik Erik - 2 months ago 16
Android Question

How can I update a single row in a ListView?

I have a

ListView
which displays news items. They contain an image, a title and some text. The image is loaded in a separate thread (with a queue and all) and when the image is downloaded, I now call
notifyDataSetChanged()
on the list adapter to update the image. This works, but
getView()
is getting called too frequently, since
notifyDataSetChanged()
calls
getView()
for all visible items. I want to update just the single item in the list. How would I do this?

Problems I have with my current approach are:


  1. Scrolling is slow

  2. I have a fade-in animation on the image which happens every time a single new image in the list is loaded.


Answer

I found the answer, thanks to your information Michelle. You can indeed get the right view using View#getChildAt(int index). The catch is that it starts counting from the first visible item. In fact, you can only get the visible items. You solve this with ListView#getFirstVisiblePosition().

Example:

private void updateView(int index){
    View v = yourListView.getChildAt(index - 
        yourListView.getFirstVisiblePosition());

    if(v == null)
       return;

    TextView someText = (TextView) v.findViewById(R.id.sometextview);
    someText.setText("Hi! I updated you manually!");
}