滑动退出View设计思路
知识点
滑动冲突的解决,立足点在于事件传递。简单的事件传递默认大家都已经知道了。在这次解决问题过程中,有几个点,我认为较为重要。
-
当子View决定处理Down以后,在父View的onInterceptTouchEvent中,决定拦截后续的某个事件,子View会收到Cancel事件。
-
当在onInterceptTouchEvent中决定拦截子View的事件,并返回true后,将不再通过onInterceptTouchEvent传递事件,而是直接传到onTouchEvent中。
-
如果在onInterceptTouchEvent返回false,可以保证后续的操作都经过,但是,无法拦截子View获得事件。
其中最重要的应该是第二点。
- 如果要求父类不要拦截点击事件,可以调用
getParent().requestDisallowInterceptTouchEvent(false);
告知父类不要拦截点击事件。
如果理解
- 如果父类拦截了,就说明,以后就我自己处理了,也就没有必要将事件继续传递给子类。我自己处理不就好了。一方面,减少不必要的传递损耗。另一方面,最少知道原则,子类不要需要处理自己不相干的事情。同时,这是一个责任链设计模式。
场景
构建一个ViewGroup,内部有一个RecyclerView,横滑退出,纵向RecyclerView滑动。
思路
这个场景很像RecyclrView的滑动事件冲突处理。即在父布局中判断哪个View可以滑动,是否阻止子View滑动。所以,在网上找了滑动事件处理的代码,加以修改。
代码
/**
* @author: guoxuan
* @version: 1.0
* @date:2021/07/21
* class desc:
*/
class SwipeBackView : ConstraintLayout {
private var scrollPointerId: Int = 0
private var initialTouchX: Int = 0
private var initialTouchY: Int = 0
private var mScreenWidth = 0
private var mTouchSlop = 0
private var mAnimator: ValueAnimator? = null
private var mVelTracker: VelocityTracker? = null
private var mCallBack: CallBack? = null
private var hasIntercept = false
private var mStartMovePx = 40
constructor(context: Context) : super(context) {
initView(context)
}
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
initView(context)
}
constructor(context: Context, attributeSet: AttributeSet, defluatStyle: Int) : super(context, attributeSet, defluatStyle) {
initView(context