概述:
Recycler视图有一个水平布局管理器,在线性布局管理器中我覆盖了canScrollHorizontally方法,因此用户无法自己滚动。
此外,我还有一个RecyclerView.SmoothScroller以编程方式更改可见项目(回收站视图附加了PagerSnapHelper,每个recylcler项目覆盖整个屏幕,使用此功能,回收站视图就像ViewPager一样)。
但是当我调用方法myRecyclerView.getLayoutManager()。startSmoothScroll(smoothScrollerForward)时,无法执行滚动,因为线性布局管理器canScrollHorizontally返回始终为false。
如果我使canScrollHorizontally方法在调用startSmoothScroll之前返回true它可以工作,但是如何知道myRecyclerView.getLayoutManager()。startSmoothScroll(smoothScrollerForward)何时结束?这样我就可以将canScrollHorizontally返回的变量再次移动到false。
以下是代码:
private RecyclerView rvCards;
private LinearLayoutManager manager;
private RecyclerView.SmoothScroller smoothScrollerForward;
private int currentPosition;
private boolean horizontalScroll = false;
rvCards = findViewById(R.id.rvCards);
manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,
false)
{
@Override
public boolean canScrollHorizontally() {
return horizontalScroll;
}
};
rvCards.setLayoutManager(manager);
PagerSnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(rvCards);
smoothScrollerForward = new LinearSmoothScroller(this){
@Override
protected int getHorizontalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_END;
}
};
ivForwardCard.setOnClickListener(v -> {
smoothScrollerForward.setTargetPosition(++currentPosition);
rvCards.getLayoutManager().startSmoothScroll(smoothScrollerForward);
});
public void changeItem(int position) {
horizontalScroll = true;
ivForwardCard.performClick();
}