你好,亲爱的观众。
我的情况:
我有一个viewpager,可让我的用户左右滑动。我有一个屏幕(一个片段),我想由用户完成才能刷卡。
我做了什么:
我自定义了viewpager以在希望锁定时锁定滑动(请参见我的代码),但是它同时禁用了两个方向。
理想情况下,我只想禁用从左向右滑动:我希望用户可以向后滑动(从右向左)。我只是想禁用向前滑动(从左到右)。
[我试图在我的视图寻呼机上实现一个onTouchListener来检测滑动方向,但仅在ViewPager解锁时才有效。
你能帮我吗?
编辑1:我还尝试过将onTouchListener放在viewpager的父布局上,但未检测到任何东西。
代码:
/**
* Class "LockableViewPager" :
* Custom viewpager that allows or not to swipe between fragments.
**/
class LockableViewPager : ViewPager {
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)
companion object {
private const val TAG = "LockableViewPager"
}
/**
* Is swiping enabled ?
*/
private var swipeEnabled = true
/**
* Intercept all touch screen motion events.
* Allows to watch events as they are dispatched, and
* take ownership of the current gesture at any point.
*
* @param event : The motion event being dispatched down the hierarchy.
* @return Return true to steal motion events from the children and have
* them dispatched to this ViewGroup through onTouchEvent().
* The current target will receive an ACTION_CANCEL event, and no further
* messages will be delivered here.
*/
override fun onTouchEvent(event: MotionEvent): Boolean {
return when (swipeEnabled) {
true -> super.onTouchEvent(event)
false -> // Do nothing.
return false
}
}
/**
* Implement this method to intercept all touch screen motion events. This
* allows you to watch events as they are dispatched to your children, and
* take ownership of the current gesture at any point.
*
* @param event : The motion event being dispatched down the hierarchy.
* @return Return true to steal motion events from the children and have
* them dispatched to this ViewGroup through onTouchEvent().
* The current target will receive an ACTION_CANCEL event, and no further
* messages will be delivered here.
*/
override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
return when (swipeEnabled) {
true -> super.onInterceptTouchEvent(event)
false -> swipeEnabled
}
}
/**
* Sets the swipeEnabled value to lock or unlock swiping
*/
fun setSwipeEnabled(swipeEnabled: Boolean) {
this.swipeEnabled = swipeEnabled
}
}
解决方案是使用physics
的NeverScrollableScrollPhysics()