Reputation: 1974
I have a listview that refreshed every 5 secs, using a XML parsing. After refreshing, the current position of the list go back to first position. Is there any possible ways to solve this?
Upvotes: 5
Views: 7249
Reputation: 3624
This code will help you out....
// get position of listview
int index = listView.getFirstVisiblePosition();
View v = listView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// notify dataset changed or re-assign adapter here
//re-assign the position of listview after setting the adapter again
listView.setSelectionFromTop(index, top);
Cheers :)
Upvotes: 2
Reputation: 2018
By using setAdapter() to update a list Android resets the position. Try altering the Adapter instead.
I don't know which adapter you're using so here two examples.
ArrayAdapter
adapter = list.getAdapter();
if (adapter == null) {
// Create new adapter + list.setAdapter()
} else {
adapter.clear();
adapter.addAll(newData);
adapter.notify(notifyDataSetChanged());
}
CursorAdapter
adapter.changeCursor(newCursor);
Upvotes: 5
Reputation: 14038
Use lv.smoothScrollToPosition(pos)
where pos could be any int, preferably the length of the adapter, if you want the listview to autoscroll to the last added entry as it is refreshed.
public void smoothScrollToPosition (int position)
Smoothly scroll to the specified adapter position. The view will scroll such that the indicated position is displayed.
Upvotes: 3