有這樣的一個需求,APP首頁佈局已經是有了幾個Fragment(fragment裏又有recyclerview,可垂直滑動)
但是這個時候,我們的Activity又想要實現監聽滑動效果,從而實現某個view的顯示和隱藏,應該如何做?
剛開始研究了下,發現只能觸發MotionEvent裏的Action_Down事件,而無法得到後續的Action_up事件
最終還是採用了一個自定義ViewGroup來攔截事件傳遞(實際並沒有攔截,只是追加了一個監聽滑動邏輯),通過dispatchTouchEvent()
方法來進行事件的分發
代碼
class CustomViewGroup : FrameLayout {
constructor(context: Context?) : super(context!!) {}
constructor(context: Context?, attrs: AttributeSet?) : super(
context!!, attrs
) {
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
//這裏只是追加個邏輯,並沒有攔截事件繼續分發(否則會導致底層的recyclerview無法滾動了)
gestureDetector.onTouchEvent(ev)
return super.dispatchTouchEvent(ev)
}
private val gestureDetector by lazy{
GestureDetector(context, gestureListener)
}
private val gestureListener = object : GestureDetector.SimpleOnGestureListener() {
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
val diffY = e2.y - e1.y
//diffY>0 表示手指向下滑動,列表向上移動
scorllAction.invoke(diffY>0)
return true
}
}
private var scorllAction = {flag:Boolean->}
//對外提供的設置滑動事件觸發
fun registerTouchEvent(action:(isUp:Boolean)->Unit) {
scorllAction = action
}
}
使用的話,將把上述的自定義View作爲Activity的根佈局即可
最終,調用上篇博客講到的動畫效果,就能夠實現常見的上滑出現一個view和下移則隱藏一個view的效果了