在 Android 中很好地设置 ListView 滚动位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3313483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:40:27  来源:igfitidea点击:

Setting ListView scroll position nicely in Android

androidlistviewscroll

提问by Carl Manaster

I am aware of setSelection(), setSelectionFromTop(), and setSelectionAfterHeaderView(), but none of them seems to do what I want.

我知道setSelection(), setSelectionFromTop(), 和setSelectionAfterHeaderView(),但他们似乎都没有做我想做的事。

Given an item in the list, I want to scroll so that it is in view. If the item is above the visible window of the list, I want to scroll until the item is the first visible item in the list; if the item is below the visible window, I want it to scroll up until it is the last visible item in the list. If the item is already visible, I don't want any scrolling to occur.

给定列表中的一个项目,我想滚动以使其可见。如果该项目在列表的可见窗口上方,我想滚动直到该项目成为列表中的第一个可见项目;如果该项目位于可见窗口下方,我希望它向上滚动,直到它成为列表中的最后一个可见项目。如果该项目已经可见,我不希望发生任何滚动。

How do I go about this?

我该怎么做?

回答by Sergey

It occurs because listView isn't created yet. Try to post runnable such as:

发生这种情况是因为尚未创建 listView。尝试发布可运行的,例如:

getListView().postDelayed(new Runnable() {          
    @Override
    public void run() {
        lst.setSelection(15);
    }
},100L);

回答by strange-corner

I think, I was looking for the same, then I found the following solution:

我想,我一直在寻找相同的东西,然后我找到了以下解决方案:

if (listview.getFirstVisiblePosition() > pos 
    || listview.getLastVisiblePosition() <= pos) {
    listview.smoothScrollToPosition(pos);
}

API 8is required to use smoothScrollToPosition(which is a reasonable minimum anyways) so you are aware.

需要使用API 8smoothScrollToPosition(无论如何这是一个合理的最低限度),所以你知道。

回答by Alessandro Roaro

Sergey's answer works, but I believe that the right way of doing this is setting up an observer to be notified when the ListViewhas been created.

Sergey 的回答有效,但我相信这样做的正确方法是设置一个观察者,以便ListView在创建时收到通知。

listView.getViewTreeObserver().addOnGlobalLayoutListener(
     new ViewTreeObserver.OnGlobalLayoutListener() {
 @Override
 public void onGlobalLayout() {
     scrollTo(scrollToPosition);
     listView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
 }
});

回答by foshoshin

A better solution to Sergey's answeris to call setSelection()later in the Activity/Fragment life cycle, perhaps in onStart(). That way, you have a guarantee that the View is ready rather than using some arbitrary delay.

Sergey 的答案的一个更好的解决方案是setSelection()在 Activity/Fragment 生命周期的后期调用,也许在onStart(). 这样,您就可以保证 View 已准备就绪,而不是使用一些任意延迟。