List view back to top postion after updating data in arrayadapter

烂漫一生 提交于 2019-12-22 07:41:59

问题


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?


回答1:


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);



回答2:


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.



回答3:


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 :)




回答4:


try this

adapter.notifyDataSetChanged();


来源:https://stackoverflow.com/questions/9870981/list-view-back-to-top-postion-after-updating-data-in-arrayadapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!