android - 如何控制 recyclerView.smoothScrollToPosition(position) 的滚动速度?

标签 android android-recyclerview

我有一个回收站 View ,我希望平滑向下滚动,然后以编程方式向上滚动以向用户显示其中的完整内容。

我可以这样做:

    final int height=recyclerView.getChildAt(0).getHeight();
    recyclerView.smoothScrollToPosition(height);
    recyclerView.postDelayed(new Runnable() {
        public void run() {
            recyclerView.smoothScrollToPosition(0);
                        }
    },200);

但我想要的是放慢滚动速度,让完整的内容清晰可见。

最佳答案

只是为了稍微改进一下答案:

public class SpeedyLinearLayoutManager extends LinearLayoutManager {

    private static final float MILLISECONDS_PER_INCH = 5f; //default is 25f (bigger = slower)

    public SpeedyLinearLayoutManager(Context context) {
        super(context);
    }

    public SpeedyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public SpeedyLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {

        final LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {

            @Override
            public PointF computeScrollVectorForPosition(int targetPosition) {
                return super.computeScrollVectorForPosition(targetPosition);
            }

            @Override
            protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
            }
        };

        linearSmoothScroller.setTargetPosition(position);
        startSmoothScroll(linearSmoothScroller);
    }
}

然后将 SpeedyLayoutManager 设置为您的 RecyclerView:

recyclerView.setLayoutManager(new SpeedyLinearLayoutManager(context, SpeedyLinearLayoutManager.VERTICAL, false);

关于android - 如何控制 recyclerView.smoothScrollToPosition(position) 的滚动速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32241948/

相关文章:

java - 在 RecyclerView 中搜索

android - 在 RecyclerView 中设置 contentInset

android - ateUpload到Bintray错误:app:compileDebugUnitTestJavaWithJavac

java - Android 11 打开失败 : EACCES (Permission denied)

android - 使用 audioSessionId 值来实例化 AudioFx 类?

android - 滚动向 TextView 添加值

android - 在适配器中获取 ArrayIndexOutOfBoundsException

java - RecyclerView 不显示任何内容

android - 处于测试模式的设备 Admob

android - 如何在 Android 资源中使用 unicode?