Android - 使用RecyclerView左右水平滚动

时间:2015-11-03 20:54:06

标签: android scroll android-recyclerview smooth

我点击了一个左或右按钮后,我自定义了一个LayoutManager来平滑滚动。只滚动左侧时一切正常!对于正确的,computeScrollVectorForPosition从不调用事件。是什么赋予了?我在向右走时尝试设置mReverseLayout,但这没有任何帮助。我还没做什么/忽视?

public class SmoothScrollLayoutManager extends LinearLayoutManager {

private static final float MILLISECONDS_PER_INCH =  50f;
private Context context;
public boolean shouldGoRight = false;

public SmoothScrollLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
    this.context = context;
}

@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
    LinearSmoothScroller smoothScroller = new LinearSmoothScroller(context) {

        @Override
        public PointF computeScrollVectorForPosition(int targetPosition) {
            if (getChildCount() == 0) {
                return null;
            }
            final int firstChildPos = getPosition(getChildAt(0));
            final int direction = targetPosition < firstChildPos != shouldGoRight ? -1 : 1;
            return new PointF(direction, 0);

        }

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

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

}

1 个答案:

答案 0 :(得分:0)

comupteScrollVectorForPosition仅被调用以找出LinearSmoothScroller必须滚动到最终找到元素的方向。如果LinearSmoothScroller已经考虑知道元素的位置,则不会调用此函数。对于已经加载的元素,就像右边的元素一样。