Android的ListView控件 - 滚动回上更新顶部(Android ListView - s

2019-06-26 21:39发布

我有一个列表视图即得到进一步意见,要求补充说,这是由一个BaseAdapter维护。 我怎样才能保持在更新后滚动位置?

我知道这已经被问了几次,但每次,相同的解决方案已经被提出来的,我都试过了,这是调用adapter.notifyDataSetChanged(); 更新包含列表内容的ArrayList中后。

我怎么能保证滚动位置保持?

Answer 1:

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

我希望这有帮助。



Answer 2:

我采取的办法是调用ListView.setSelection(position)滚动到期望的position在更新之后。

这取决于你是从调用它,您可能需要调用requestFocusFromTouch调用之前setSelection ,以确保得到适当位置的项目。



Answer 3:

这个代码将会帮助你....

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

干杯:)



Answer 4:

你可以试试这个:

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


Answer 5:

你可以如下做到。 如果你想与滚动加载更多的数据,底部也将有一些变化。

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
    }
}


文章来源: Android ListView - scrolls back to top on update