Best way to "update" and "setSelection" after updating the ListView (android)

In mine ListView

I select the Add Favorite item and I need to do something, I fill in the data again to update the list, then I implement OnScrollListener

use setSelection(firstVisibleItem)

to set the display of the list to the right of the added item.

Is there a better way to do this. I mean mCursor.requery()

or something similar in Android APIs. Or any way to suggest?

+2


source to share


5 answers


To display the selected item in the middle rather than the top of mine ListView

, I used setSelectionFromTop()

:

getListView().setSelectionFromTop(pos, getListView().getHeight() / 2);

      



Of course, you could additionally subtract half the height of your cell from the division above to get a selection exactly in the middle.

+5


source


Well, that requery()

is the preferred way to repopulate ListView

that is supported SimpleCursorAdapter

. Calling setSelection()

on ListView

seems like a great way to provide a visible element. I don't quite understand what OnScrollListener

has to do with any of this.



+1


source


If you just call it setSelection()

, it will make your element look unnatural . For example, if your item is displayed in the "middle" of the screen and its position is 8. When you add favorites, update data, setSelection (8), the item will appear "on top" of the screen (rather, it is in the "middle").

So that's why I use OnScrollListener

to get firstVisibleItem

and use that value to set the position. This makes the display look natural. This is the function:

public void onScroll(AbsListView view, int firstVisibleItem, int VisibleItemCount, int totalItemCount){}

      

I think this happens a lot with everyone who updates data in ListView

. And I hope someone can share their experience on this issue.

+1


source


mListActivity.runOnUiThread(
    new Runnable() {
        public void run() {
            x.setSelection(x.getCount());
        } 
    } 
);

      

+1


source


This is what you are all looking for:

onResume()
{
    refresh_your_data()
    if(listview.getadapter()==null)
     // create the adapter
    }
    else
    {
        adapter.notifydatasetchanged();
    }
}

      

+1


source







All Articles