Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List view back to top postion after updating data in arrayadapter

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?

like image 445
ASP Avatar asked Mar 26 '12 11:03

ASP


2 Answers

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);
like image 79
flo Avatar answered Nov 15 '22 07:11

flo


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.
like image 26
Akhil Avatar answered Nov 15 '22 07:11

Akhil