RecyclerView smoothScrollToPosition返回错误的位置

时间:2019-06-11 07:15:13

标签: android android-recyclerview android-animation android-scrollview

在我的recyclerView中,我想按位置滚动动画。我写了自定义的LinearLayoutManager。

这是我的代码

public class CustomLayoutManager extends LinearLayoutManager {
    private static final float MILLISECONDS_PER_INCH = 200f;
    private Context mContext;

    public CustomLayoutManager(Context context) {
        super(context);
        mContext = context;
    }

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

        LinearSmoothScroller smoothScroller =
            new LinearSmoothScroller(mContext) {
                @Override
                public PointF computeScrollVectorForPosition
                (int targetPosition) {
                    return CustomLayoutManager.this
                            .computeScrollVectorForPosition(targetPosition);
                }
                @Override
                protected float calculateSpeedPerPixel
                (DisplayMetrics displayMetrics) {
                    return MILLISECONDS_PER_INCH/displayMetrics.densityDpi;
                }
            };

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

我正在像这样使用此类。

leaderBoardAdapter = new SPGamificationLeaderBoardAdapter(response.list, getContext());
    leaderBoardRecyclerView.setAdapter(leaderBoardAdapter);
    CustomLayoutManager layoutManager = new CustomLayoutManager(getContext());
    leaderBoardRecyclerView.setLayoutManager(layoutManager);
    leaderBoardRecyclerView.post(() -> {
        leaderBoardRecyclerView.setHasFixedSize(true);
        leaderBoardRecyclerView.setNestedScrollingEnabled(false);
        leaderBoardRecyclerView.smoothScrollToPosition(10);


    });

动画运行正常,但是smoothScrollToPosition返回错误的位置。谁能向我解释我的代码有什么问题? 谢谢

1 个答案:

答案 0 :(得分:0)

替换此行

return CustomLayoutManager.this.computeScrollVectorForPosition(targetPosition);

TO

return CustomLayoutManager.this.computeScrollVectorForPosition(position);