How can I update a single row in a ListView? How can I update a single row in a ListView? android android

How can I update a single row in a ListView?


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!");}


This question has been asked at the Google I/O 2010, you can watch it here:

The world of ListView, time 52:30

Basically what Romain Guy explains is to call getChildAt(int) on the ListView to get the view and (I think) call getFirstVisiblePosition() to find out the correlation between position and index.

Romain also points to the project called Shelves as an example, I think he might mean the method ShelvesActivity.updateBookCovers(), but I can't find the call of getFirstVisiblePosition().

AWESOME UPDATES COMING:

The RecyclerView will fix this in the near future. As pointed out on http://www.grokkingandroid.com/first-glance-androids-recyclerview/, you will be able to call methods to exactly specify the change, such as:

void notifyItemInserted(int position)void notifyItemRemoved(int position)void notifyItemChanged(int position)

Also, everyone will want to use the new views based on RecyclerView because they will be rewarded with nicely-looking animations! The future looks awesome! :-)


This is how I did it:

Your items (rows) must have unique ids so you can update them later. Set the tag of every view when the list is getting the view from adapter. (You can also use key tag if the default tag is used somewhere else)

@Overridepublic View getView(int position, View convertView, ViewGroup parent){    View view = super.getView(position, convertView, parent);    view.setTag(getItemId(position));    return view;}

For the update check every element of list, if a view with given id is there it's visible so we perform the update.

private void update(long id){    int c = list.getChildCount();    for (int i = 0; i < c; i++)    {        View view = list.getChildAt(i);        if ((Long)view.getTag() == id)        {            // update view        }    }}

It's actually easier than other methods and better when you dealing with ids not positions! Also you must call update for items which get visible.