我有一个简单的活动,它有一个根布局。根布局包含一个 recyclerview。Recyclerview 将包含从 items.xml 创建的 20 个项目,其中包含 3 个文本视图。这里 items.xml 代表 recyclerview 中的单个项目。
回收站视图可以双向滚动,它是 1 到 20 之间项目的循环。
无论滑动/甩动的速度如何,我都需要仅平滑滚动 4 个项目。
我尝试了很多方法但直到现在都无法成功的方法。如果有人可以提出任何建议,那将非常有帮助。
SnapHelper - 这似乎只捕捉中心的项目。
使用手势检测器 - 所有动作都检测到手势,但我无法阻止 recyclerview 的默认滚动行为。
主要问题是由于用户滚动和甩动速度的变化导致回收站视图过度滚动。
这是我为手势检测器设置的。
public myRecyclerTouchListner(final Context context, final RecyclerView recycleView,
final LinearLayoutManager linearLayoutManager,
final ClickListener clicklistener){
final ViewConfiguration vc = ViewConfiguration.get(context);
final int swipeMinDistance = vc.getScaledPagingTouchSlop();
final int swipeThresholdVelocity = vc.getScaledMinimumFlingVelocity();
final int swipeMaxOffPath = vc.getScaledTouchSlop();
this.clicklistener=clicklistener;
simpleGestureDetector =new GestureDetector(context,new GestureDetector.SimpleOnGestureListener( ){
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.d("try", "on Fling called");
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE &&
Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//From Right to Left
recycleView.smoothScrollToPosition(linearLayoutManager.
findLastCompletelyVisibleItemPosition() + Constants.spanLength);
return true;
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE &&
Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//From Left to Right
recycleView.smoothScrollToPosition(linearLayoutManager.
findFirstCompletelyVisibleItemPosition() - Constants.spanLength);
return true;
}
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
Log.d("Try", "Long press gesture");
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}
});