smoothScrollToPosition在recyclerView中不起作用

时间:2019-06-12 13:14:13

标签: android android-recyclerview android-animation android-xml

我创建了自定义的LinearLayoutManager类,我的目标是使smoothScrollToPosition带有动画。这是我的代码:

public class LinearLayoutManagerWithSmoothScroller extends LinearLayoutManager {
private static final float MILLISECONDS_PER_INCH = 100f;

public LinearLayoutManagerWithSmoothScroller(Context context) {
    super(context, VERTICAL, false);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
                                   int position) {
    RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext());
    smoothScroller.setTargetPosition(position);
    startSmoothScroll(smoothScroller);
}

private class TopSnappedSmoothScroller extends LinearSmoothScroller {
    public TopSnappedSmoothScroller(Context context) {
        super(context);

    }

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

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

    @Override
    protected int getVerticalSnapPreference() {
        return SNAP_TO_START;
    }
}

}

此外,我在RecyclerView中创建了自定义LayoutAnimation。这是xml代码

<layoutAnimation
xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="@anim/item_animation_from_bottom"
android:delay="15%"
android:animationOrder="normal"
/>

这是我的Java代码。

        leaderBoardAdapter = new SPGamificationLeaderBoardAdapter(response.list, getContext());
    leaderBoardRecyclerView.setAdapter(leaderBoardAdapter);
    leaderBoardRecyclerView.setHasFixedSize(true);
    leaderBoardRecyclerView.setNestedScrollingEnabled(false);

    LayoutAnimationController controller =
            AnimationUtils.loadLayoutAnimation(getContext(), R.anim.layout_animation_from_bottom);
    leaderBoardRecyclerView.setLayoutManager(smoothScroller);

    leaderBoardRecyclerView.setLayoutAnimation(controller);
    leaderBoardRecyclerView.scheduleLayoutAnimation();
    leaderBoardRecyclerView.post(() -> leaderBoardRecyclerView.smoothScrollToPosition(getPosition(response)));

我的问题是,两个选项(smoothScrollToPosition和LayoutAnimation)不能同时工作。我删除了smoothScrollToPosition和布局动画,并删除了smoothScrollToPosition-布局动画已经起作用。 有什么办法可以同时使用这两个功能?我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

您可以使用scrollToPosition(itemNo)来实现自己的目标。

像下面这样:

recyclerview.scrollToPosition(20);

使用smoothScrollToPosition,项目滚动非常快,这就是为什么动画不起作用的原因。