android - 限制用户在 RecyclerView 中滚动
问题描述
在我的项目中,我使用了一个 RecyclerView,我只想通过调用 LayoutManager 的 startSmoothScroll() 方法来滚动它:
private fun next(){
val layoutManager = pager.layoutManager as BattlePageLayoutManager
layoutManager.startSmoothScroll(smoothScroller(layoutManager.findFirstVisibleItemPosition() + 1))
layoutManager.finishScroll()
}
我不希望用户能够手动滚动,例如通过滑动。
我已经尝试通过覆盖父 FrameLayout 的 onInterceptTouchEvent() 方法来实现这一点。
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
if (ev.actionMasked == MotionEvent.ACTION_DOWN){
startClickTime = System.currentTimeMillis()
startX = ev.x
startY = ev.y
}
val allowEvent = (System.currentTimeMillis() - startClickTime) < 1000 && (startX-ev.x).absoluteValue < 15 && (startY-ev.y).absoluteValue < 15
return !allowEvent
}
这基本上是有效的,但是在双击视图后,用户可以自己滚动。
你有其他想法来解决这个问题吗?
解决方案
您是否尝试在 LayoutManager 中覆盖 canScrollVertically() 方法?
mLayoutManager = new LinearLayoutManager(getActivity()) {
@Override
public boolean canScrollVertically() {
return false;
}
};
编辑:
创建您自己的 RecyclerView 实现,它在滚动执行时禁用触摸事件。然后您必须更改 xml 文件中的 RecyclerView 类和 Fragment/Activity 。
在此处找到 Kotlin 中的示例
class MyRecyclerView : RecyclerView {
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {}
override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
return if (scrollState != RecyclerView.SCROLL_STATE_IDLE) false else super.onInterceptTouchEvent(e)
}
}
在Java中
public class MyRecyclerView extends RecyclerView {
public MyRecyclerView(Context context) {
super(context);
}
public MyRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if(getScrollState() != SCROLL_STATE_IDLE)
return false;
return super.onInterceptTouchEvent(e);
}
}
推荐阅读
- ios - 如何将从该请求收到的数据或 json 附加到一个空数组?
- python - 人员组中所需的最少面孔 - Azure Face Api
- python - 什么条件会导致 itertools.groupby() 源代码中的 while 循环停止
- python - 研究你的大学
- javascript - Javascript 中的 Thrift TMemoryBuffer 传输
- tinymce - 为什么tinymce会将内容移出
tags? - or auto-close the tags?
- javascript - 新手问题:从 ajax 调用传递错误消息的正确方法是什么?
- python-3.x - How do I check whether a windows program is running or not?
- cplex - 如何创建具有目标优先级的多目标模型
- angular - asp.net core 2.1 和 angular 中的 CORS