[Android]RecycleView 的空白部分添加長按事件
需求
需要一個類似電腦上的那種,即使是空白也能夠長按,雖然空白部分與非空白部分不同。
探求
查找了一些資料,有一個講到一個奇怪的東西,類型與自動識別了所有的操作類型,其中有長按,只可惜找不到了,在Android 中也查不到,我恨我自己當時沒有測試。
然後去查看View 的長按事件,感覺好麻煩,好像監聽事件不是由View 本身去做的。
然後在
stackoverflow
上找到了,辦法是通過OnItemTouchListener
。
解決
-
方法是
/** * Add an {@link OnItemTouchListener} to intercept touch events before they are dispatched * to child views or this view's standard scrolling behavior. * * <p>Client code may use listeners to implement item manipulation behavior. Once a listener * returns true from * {@link OnItemTouchListener#onInterceptTouchEvent(RecyclerView, MotionEvent)} its * {@link OnItemTouchListener#onTouchEvent(RecyclerView, MotionEvent)} method will be called * for each incoming MotionEvent until the end of the gesture.</p> * * @param listener Listener to add * @see SimpleOnItemTouchListener */ public void addOnItemTouchListener(@NonNull OnItemTouchListener listener) { mOnItemTouchListeners.add(listener); }
說的是會在分發到子對象和滾動事件之前攔截。
如果onInterceptTouchEvent
返回值true
後面一連串的事件都由onTouchEvent
處理,不過我們當前用不到,直接返回false
得了。 -
添加,並實現
onInterceptTouchEvent
。Log.d(TAG, "onInterceptTouchEvent() called with: rv = [" + rv + "], e = [" + e + "]"); if (e.getAction() == MotionEvent.ACTION_UP) { long l = e.getEventTime() - e.getDownTime(); Log.i(TAG, "onTouchEvent: l:"+l); if (l > 900) { //TODO long click event } } } return false;
事件本事會記錄按下時間,當取消按下時獲取時間差即可。
實際測試,感覺設置900
即可。
如果需要長按中滑動就取消此次事件的話請自行實現。