A common problem, at least for me, in Android development is how to update a single item in a ListView. I needed this when I wanted to add a fade-in animation of images in a newsreader, where placeholder images were replaced by the actual article images with a fade-in animation.
First, the problem: When the ‘content’ of a list item should update, you usually call notifyDataSetChanged() on your listadapter. When you do this, all visible items are redrawn, resulting in up-to-date views. If, for example, drawing the list item has an animation to it, all the list items will animate (again). Additionally, this will keep happening constantly when the user scrolls, since Android will redraw your view once the item is going from invisible (outside of the screen) to visible.
Next, the solution: Get the view of the item you want to update and do something with this single view. This can be accomplished by calling getViewAt(int index) on your ListView instance. The catch is that this method only return views that are visible, starting with the first visible item. Luckily, you can call getFirstVisiblePosition() on your ListView instance to get the index of the first item that is visible on the screen. You can then easily calculate the index of the view you want to update. So, to update a single view, you can do something like this:
private void updateView(int itemIndex){
int visiblePosition = yourListView.getFirstVisiblePosition();
View v = yourListView.getChildAt(itemIndex - visiblePosition);
// Do something fancy with your listitem view
TextView someTextView = (TextView) v.findViewById(R.id.sometextview);
someTextView.setText("Hi! I updated you manually!");
}
See? You just updated a view without calling notifyDataSetChanged()! Keep in mind that this updated view is not persistent, so when the view get’s scrolled out of sight and later returns on the screen, it will be redrawn by the listadapter, thus discarding whatever changes you made manually. However, this is not a problem if you update the contents of whatever object your listadapter uses to draw a list item.
Keep in mind that this is only useful when you want to do something fancy with your list item, like an animation or something performance-related.
