简体   繁体   English

Listview平滑滚动,直到项目位于顶部

[英]Listview smooth scroll until item is at top

I am working on an android application, I have a list view with 10 items. 我正在开发一个android应用程序,我有一个包含10个项目的列表视图。 I need to do the following. 我需要执行以下操作。 When the user clicks a button, I want the list to smooth scroll to item at position 5, so this item is displayed on the top of the list. 当用户单击按钮时,我希望列表平滑滚动到位置5的项目,因此该项目显示在列表的顶部。

I have found 2 methods that can be used for this, but both methods are not working exactly how I need: 我发现有2种方法可用于此目的,但两种方法均无法完全满足我的需要:

listView.setSelection(5) this will scroll to the row and put it on top of the list But without animation listView.setSelection(5)这将滚动到该行并将其放在列表顶部,但没有动画

list.smoothScrollToPosition(5) this will scroll the listview untill the row is visible but it will not put it on top (it is at the bottom of the page) and if the row is allready visible it will not scroll as it considers it is visible. list.smoothScrollToPosition(5)这将滚动列表视图,直到该行可见,但不会将其放在顶部(它位于页面底部),并且如果该行已经可见,则不会滚动,因为它认为是可见。

So is there a way to have the same behavior as the setSelection method but with smoothscrolling? 那么,有没有一种方法与setSelection方法具有相同的行为,但可以平滑滚动?

Thank you 谢谢

I believe smoothScrollToPositionFromTop() does what you want. 我相信smoothScrollToPositionFromTop()可以满足您的需求。

There's also one that will take the desired animation duration in milliseconds as an argument. 还有一种将所需的动画持续时间(以毫秒为单位)作为参数。

So is there a way to have the same behavior as the setSelection method but with smoothscrolling? 那么,有没有一种方法与setSelection方法具有相同的行为,但可以平滑滚动?

You could post a delayed Runnable and create your own smooth scroll effect using ListView.setSelection . 您可以发布延迟的Runnable并使用ListView.setSelection创建自己的平滑滚动效果。 Here's an example: 这是一个例子:

private ListView mListView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    mListView.post(new PositionScroller(this));
}

private static final class PositionScroller implements Runnable {

    private static final int SMOOTH_SCROLL_DURATION = 25;
    private int mSelectedPosition;

    private final WeakReference<YourParentActivity> mParent;

    private PositionScroller(YourParentActivity parent) {
        mParent = new WeakReference<YourParentActivity>(parent);
    }

    @Override
    public void run() {
        final ListView list = mParent.get().mListView;
        if (mSelectedPosition <= 5) {
            if (list.postDelayed(this, SMOOTH_SCROLL_DURATION)) {
                list.setSelection(mSelectedPosition++);
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM