smoothScrollToPositionFromTop()并不总是像它应该的那样工作

时间:2013-01-23 11:52:14

标签: android

我一直试图让smoothScrollToPositionFromTop()工作,但它并不总是滚动到正确的位置。

我在一个布局中有一个ListView(有10个项目),旁边有10个按钮,所以我可以滚动到列表中的每个项目。通常当我向后或向前滚动一个位置时它工作正常,但是当我尝试向后或向前滚动超过3个位置时,ListView并不完全在所选位置结束。当它失败时,通常会关闭0.5到1.5个项目,当滚动失败时它不能真正预测。

我还检查了smoothScrollToPosition after notifyDataSetChanged not working in android,但此修复程序对我不起作用,我不会更改任何数据。

我真的想自动滚动到所选的列表项,但不是我无法弄清楚如何。有没有人以前遇到过这个问题并且知道如何修复它?

5 个答案:

答案 0 :(得分:50)

这是一个已知的错误。见https://code.google.com/p/android/issues/detail?id=36062

但是,我实施了此解决方法,处理可能发生的所有边缘情况:

首先调用smothScrollToPositionFromTop(position),然后在滚动完成后,调用setSelection(position)。后一个调用通过直接跳到所需位置来纠正不完整的滚动。这样做,用户仍然会感觉它正在动画滚动到此位置。

我在两个辅助方法中实现了这个解决方法:

<强> smoothScrollToPositionFromTop()

public static void smoothScrollToPositionFromTop(final AbsListView view, final int position) {
    View child = getChildAtPosition(view, position);
    // There's no need to scroll if child is already at top or view is already scrolled to its end
    if ((child != null) && ((child.getTop() == 0) || ((child.getTop() > 0) && !view.canScrollVertically(1)))) {
        return;
    }

    view.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(final AbsListView view, final int scrollState) {
            if (scrollState == SCROLL_STATE_IDLE) {
                view.setOnScrollListener(null);

                // Fix for scrolling bug
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        view.setSelection(position);
                    }
                });
            }
        }

        @Override
        public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount,
                                 final int totalItemCount) { }
    });

    // Perform scrolling to position
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            view.smoothScrollToPositionFromTop(position, 0);
        }
    });
}

<强> getChildAtPosition()

public static View getChildAtPosition(final AdapterView view, final int position) {
    final int index = position - view.getFirstVisiblePosition();
    if ((index >= 0) && (index < view.getChildCount())) {
        return view.getChildAt(index);
    } else {
        return null;
    }
}

答案 1 :(得分:3)

以下是解决方案的实现。

    void smoothScrollToPositionFromTopWithBugWorkAround(final AbsListView listView,
                                                    final int position,
                                                    final int offset, 
                                                    final int duration){

    //the bug workaround involves listening to when it has finished scrolling, and then 
    //firing a new scroll to the same position.

    //the bug is the case that sometimes smooth Scroll To Position sort of misses its intended position. 
    //more info here : https://code.google.com/p/android/issues/detail?id=36062
    listView.smoothScrollToPositionFromTop(position, offset, duration);
    listView.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if(scrollState==OnScrollListener.SCROLL_STATE_IDLE){
                listView.setOnScrollListener(null);
                listView.smoothScrollToPositionFromTop(position, offset, duration);
            }

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    });
}

答案 2 :(得分:0)

正如四楼google issuetracker页面所述:https://issuetracker.google.com/issues/36952786

  

前面给出的解决方法,“现在的解决方法是在启动滚动时侦听SCROLL_STATE_IDLE,并将smoothScrollToPositionFromTop再次侦听到相同的位置。”也不会一直有效。

实际上,使用SCROLL_STATE_IDLE调用onScrollStateChanged并不一定意味着滚动已完成。因此,它仍然无法保证Listview每次都滚动到正确的位置,尤其是当列表项视图不是全部在同一高度时。

经过研究,我发现另一种方法可以正确合理地工作。众所周知,Listview提供了一个方法scrollListBy(int y),它使我们能够立即向上滚动Listview y像素。然后,在计时器的帮助下,我们可以自己平滑地正确滚动列表。

我们需要做的第一件事是计算每个列表项视图的高度,包括屏幕外的视图。由于之前已知列表数据和子视图的类型,因此计算每个列表项视图的高度是可行的。因此,给定目标位置以平滑滚动,我们可以计算其在y方向上的滚动距离。此外,应在完成ListView初始化后进行计算。

第二件事是组合一个计时器和scrollListBy(int)方法。实际上我们可以使用android.os.Handler的sendEmptyMessageDelayed()方法。因此,解决方案可以是:

/**
 * Created by CaiHaozhong on 2017/9/29.
 */
public class ListViewSmoothScroller {

    private final static int MSG_ACTION_SCROLL = 1;

    private final static int MSG_ACTION_ADJUST = 2;

    private ListView mListView = null;

    /* The accumulated height of each list item view */
    protected int[] mItemAccumulateHeight = null;

    protected int mTimeStep = 20;

    protected int mHeaderViewHeight;

    private int mPos;

    private Method mTrackMotionScrollMethod = null;

    protected int mScrollUnit = 0;

    protected int mTotalMove = 0;

    protected int mTargetScrollDis = 0;

    private Handler mMainHandler = new Handler(Looper.getMainLooper()){

        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what){
                case MSG_ACTION_SCROLL: {
                    int scrollDis = mScrollUnit;
                    if(mTotalMove + mScrollUnit > mTargetScrollDis){
                        scrollDis = mTargetScrollDis - mTotalMove;
                    }
                    if(Build.VERSION.SDK_INT >= 19) {
                        mListView.scrollListBy(scrollDis);
                    }
                    else{
                        if(mTrackMotionScrollMethod != null){
                            try {
                                mTrackMotionScrollMethod.invoke(mListView, -scrollDis, -scrollDis);
                            }catch(Exception ex){
                                ex.printStackTrace();
                            }
                        }
                    }
                    mTotalMove += scrollDis;
                    if(mTotalMove < mTargetScrollDis){
                        mMainHandler.sendEmptyMessageDelayed(MSG_ACTION_SCROLL, mTimeStep);
                    }else {
                        mMainHandler.sendEmptyMessageDelayed(MSG_ACTION_ADJUST, mTimeStep);
                    }
                    break;
                }
                case MSG_ACTION_ADJUST: {
                    mListView.setSelection(mPos);                     
                    break;
                }
            }
        }
    };

    public ListViewSmoothScroller(Context context, ListView listView){
        mListView = listView;
        mScrollUnit = Tools.dip2px(context, 60);
        mPos = -1;
        try {
            mTrackMotionScrollMethod = AbsListView.class.getDeclaredMethod("trackMotionScroll", int.class, int.class);
        }catch (NoSuchMethodException ex){
            ex.printStackTrace();
            mTrackMotionScrollMethod = null;
        }
        if(mTrackMotionScrollMethod != null){
            mTrackMotionScrollMethod.setAccessible(true);
        }
    }

    /* scroll to a target position smoothly */
    public void smoothScrollToPosition(int pos){
        if(mListView == null)
            return;
        if(mItemAccumulateHeight == null || pos >= mItemAccumulateHeight.length){
            return ;
        }
        mPos = pos;
        mTargetScrollDis = mItemAccumulateHeight[pos];
        mMainHandler.sendEmptyMessage(MSG_ACTION_SCROLL);
    }

    /* call after initializing ListView */
    public void doMeasureOnLayoutChange(){
        if(mListView == null){
            return;
        }
        int headerCount = mListView.getHeaderViewsCount();
        /* if no list item */
        if(mListView.getChildCount() < headerCount + 1){
            return ;
        }
        mHeaderViewHeight = 0;
        for(int i = 0; i < headerCount; i++){
            mHeaderViewHeight += mListView.getChildAt(i).getHeight();
        }
        View firstListItemView = mListView.getChildAt(headerCount);
        computeAccumulateHeight(firstListItemView);
    }

    /* calculate the accumulated height of each list item */
    protected void computeAccumulateHeight(View firstListItemView){
        int len = listdata.size();// count of list item
        mItemAccumulateHeight = new int[len + 2];
        mItemAccumulateHeight[0] = 0;
        mItemAccumulateHeight[1] = mHeaderViewHeight;
        int currentHeight = mHeaderViewHeight;
        for(int i = 2; i < len + 2; i++){
            currentHeight += getItemHeight(firstListItemView);
            mItemAccumulateHeight[i] = currentHeight;
        }
    }

    /* get height of a list item. You may need to pass the listdata of the list item as parameter*/
    protected int getItemHeight(View firstListItemView){
        // Considering the structure of listitem View and the list data in order to calculate the height.
    }

}

在完成ListView的初始化之后,我们调用doMeasureOnLayoutChange()方法。之后,我们可以通过smoothScrollToPosition(int pos)方法滚动ListView。我们可以像这样调用doMeasureOnLayoutChange()方法:

mListAdapter.notifyDataSetChanged();
mListView.post(new Runnable() {
    @Override
    public void run() {
        mListViewSmoothScroller.doMeasureOnLayoutChange();
    }
});

最后,我们的ListView可以顺利滚动到目标位置,更重要的是,正确滚动。

答案 3 :(得分:0)

尝试将高度从“ wrap_content”更改为“ match_parent”

<RecyclerView   
android: layout_height="match_parent" 
... >

smothScrollToPosition(0)     // works ok 

答案 4 :(得分:0)

这是Lars Blumberg在Kotlin的回答,包括dira的评论,对我有用。

private fun smoothScrollToPositionFromTop(listView: AbsListView, position: Int, offset: Int) {

    listView.setOnScrollListener(object : AbsListView.OnScrollListener {

        override fun onScroll(
            view: AbsListView?,
            firstVisibleItem: Int,
            visibleItemCount: Int,
            totalItemCount: Int
        ) { }

        override fun onScrollStateChanged(view: AbsListView?, scrollState: Int) {
            view?.setOnScrollListener(null)

            // Fix for scrolling bug.
            if (scrollState == SCROLL_STATE_IDLE) {
                Handler(Looper.getMainLooper()).post {
                    listView.setSelectionFromTop(position, offset)
                }
            }
        }
    })

    // Perform scrolling to position
    Handler(Looper.getMainLooper()).post {
        listView.smoothScrollToPositionFromTop(position, offset)
    }
}