带有SnapHelper的RecyclerView上的有害反弹效果

rus*_*ush 5 android android-recyclerview linearlayoutmanager

我正在将RecyclerView与Horizo​​ntal LinearLayoutManager一起使用。

recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));

为了将适配器项卡在中间,我将LinearSnapHelper附加到了recyclerview。

SnapHelper helper =新的LinearSnapHelper();

helper.attachToRecyclerView(recyclerView);

现在,我有两种情况希望将物品放到中心

  1. 当我的活动启动时,它应该以特定项目为中心启动。
  2. 在recyclerview中点击某个项目时,它应该居中。为此,我重写了适配器的ViewHolder中的OnClick方法。

对于这两种情况,我正在使用

recyclerView.smoothScrollToPosition(position);

物品就居中了。但是,这发生在有弹性的动画中,其中首先会发生一些额外的滚动,然后将其弹回。

如何禁用此弹性动画以平滑滚动?

我尝试过的事情-在下面的API中代替了smoothScrollToPosition

  1. LinearLayoutManager.scrollToPosition()
  2. LinearLayoutManager.scrollToPositionWithOffset()

上面的两个API都无法流畅滚动,而且项目无法正确居中(因为很难找出在API调用期间尚未创建/回收的项目的正确偏移值)

我在RecyclerView的文档中找不到任何禁用/覆盖动画的方法。有人可以帮忙吗..

小智 2

解决方案是使用扩展的 LinearLayoutManager:

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;

public class NoBounceLinearLayoutManager extends LinearLayoutManager {

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

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, final int position) {
        LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {
            @Override
            protected int getHorizontalSnapPreference() {
                return position > findFirstVisibleItemPosition() ? SNAP_TO_START : SNAP_TO_END;
            }
        };
        linearSmoothScroller.setTargetPosition(position);
        startSmoothScroll(linearSmoothScroller);
    }
}
Run Code Online (Sandbox Code Playgroud)