Better way for "refresh" and "setSelection" after Update ListView (android)
In my ListView
, I choose an Item to "Add Favorite" and I have to do some stuff work, I fill data again to refresh the List, then I implement OnScrollListener
use setSelection(firstVisibleItem)
to set List display right on Item was added.
Are there any better way to do that. 开发者_如何转开发I mean like mCursor.requery()
or something like that in android APIs ? Or any suggest way?
To display the selected item rather at the middle than at the top of my ListView
, I used setSelectionFromTop()
:
getListView().setSelectionFromTop(pos, getListView().getHeight() / 2);
Of course you could additionally subtract half of your cell layout's height from the division above to get the selection exactly in the middle.
Well, requery()
is the preferred way to repopulate a ListView
that is backed by a SimpleCursorAdapter
. Calling setSelection()
on the ListView
seems like a fine way to ensure the desired item is visible. I am unclear what the OnScrollListener
has to do with any of this.
If you just call setSelection()
, that will make your item display in unnaturally. For example, If your item is visible at the 'middle' of the screen and its position is 8. When you add favorite, refresh data, setSelection(8) the Item will display on 'top' of the screen (rather it is in the 'middle').
So, that why I use OnScrollListener
to get firstVisibleItem
and use this value to set position. It makes the item display naturally. This is the function:
public void onScroll(AbsListView view, int firstVisibleItem, int VisibleItemCount, int totalItemCount){}
I think It happens frequently with anyone who updates data in ListView
. And I hope someone can share experience in this problem.
mListActivity.runOnUiThread(
new Runnable() {
public void run() {
x.setSelection(x.getCount());
}
}
);
This is what you all are looking:
onResume()
{
refresh_your_data()
if(listview.getadapter()==null)
// create the adapter
}
else
{
adapter.notifydatasetchanged();
}
}
精彩评论