我有一个listview,可以根据请求添加其他视图,这些视图由BaseAdapter维护。如何在更新后保持滚动位置?
我知道这已被问过几次,但每次都提出了相同的解决方案,我已经尝试过,这是在更新包含列表内容的ArrayList之后调用adapter.notifyDataSetChanged();
。 / p>
如何确保保持滚动位置?
答案 0 :(得分:12)
在您的活动类中实施OnScrollListener
,然后使用以下代码:
int currentFirstVisibleItem, currentVisibleItemCount, currentTotalItemCount;
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.currentTotalItemCount = totalItemCount;
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (currentFirstVisibleItem + currentVisibleItemCount >= currentTotalItemCount) {
if (this.currentVisibleItemCount > 0
&& this.currentScrollState == SCROLL_STATE_IDLE) {
//Do your work
}
}
}
如果您使用AsyncTask
更新数据,则可以在PostExecute()
中加入以下内容以保持滚动位置:
list.setAdapter(adapter);
list.setSelectionFromTop(currentFirstVisibleItem, 0);
我希望这会有所帮助。
答案 1 :(得分:5)
我采取的方法是在更新后调用ListView.setSelection(position)
滚动到所需的position
。
根据您拨打电话的位置,您可能需要在致电requestFocusFromTouch
之前致电setSelection
,以确保项目的位置正确。
答案 2 :(得分:4)
此代码可以帮助您....
// 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);
干杯:)
答案 3 :(得分:2)
你可以试试这个:
//Get the top position from the first visible element
int fVisible = list.getFirstVisiblePosition();
View vFirst = list.getChildAt(0);
int pos = 0;
if (vFirst != null) pos = vFirst.getTop();
//Restore the position
list.setSelectionFromTop(fVisible, pos);
答案 4 :(得分:0)
您可以执行以下操作。如果你想通过滚动到底部加载更多数据,它会有一些变化。
int currentFirstVisibleItem, currentScrollState;
int countChange = 0;
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
Log.d("Scroll", "Scrolling");
this.currentFirstVisibleItem = firstVisibleItem;
countChange = 0;//during touching you can decide not to refresh by scroll
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
Log.d("Scroll", "Changed");
this.currentScrollState = scrollState;
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
countChange = 0;
}
if (++countChange > 1) {
//scroll to top and release touch change=2. Simple scroll and release touch change=1
this.isScrollCompleted();
countChange = 0;
}
}
private void isScrollCompleted() {
Log.d("Load", "Reload");
if (currentFirstVisibleItem == 0) {
//Your loading go here
}
}