【问题标题】:RecyclerView smoothScrollToPosition returning wrong positionRecyclerView smoothScrollToPosition 返回错误的位置
【发布时间】:2019-06-11 07:15:13
【问题描述】:

在我的 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 返回了错误的位置。谁能向我解释我的代码有什么问题? 谢谢

【问题讨论】:

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


    【解决方案1】:

    替换这一行

    return CustomLayoutManager.this.computeScrollVectorForPosition(targetPosition);

    return CustomLayoutManager.this.computeScrollVectorForPosition(position);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多