遇到一種狀況須要處理,RecyclerView所在Activity須要處理滑動事件用於返回(onBackPressed)。ide
手勢檢測:this
1 @Override 2 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, 3 float velocityY) { 4 LogUtil.d(this,"fling"); 5 if (e1.getX() - e2.getX() > verticalMinDistance 6 && Math.abs(velocityX) > minVelocity) { 7 LogUtil.d(this, "fling left"); 8 return true; 9 } else if (e2.getX() - e1.getX() > verticalMinDistance 10 && Math.abs(velocityX) > minVelocity) { 11 LogUtil.d(this, "fling right"); 12 activity.onBackPressed(); 13 return true; 14 } 15 return false; 16 } 17 18 @Override 19 public boolean onDown(MotionEvent e) { 20 LogUtil.d(this, "Down"); 21 return false; 22 } 23 24 @Override 25 public boolean onScroll(MotionEvent e1, MotionEvent e2, 26 float distanceX, float distanceY) { 27 LogUtil.d(this, "scroll"); 28 return false; 29 }
此處須要注意,onDown不能直接處理成true(開始就坑在這裏,徹底按普通觸摸事件處理成返回true,致使click事件永遠不會獲得事件觸發)。spa
雖然官方文檔建議處理觸摸事件時,要將其置成true,表示開始處理觸摸。但由於咱們還有itemView的click事件要處理,因此onDown不能直接返回true.code
綁定觸摸事件:blog
1 view.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() { 2 @Override 3 public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { 4 LogUtil.d("Base RecyclerView Event", "Touch"); 5 mDetector.onTouchEvent(e); 6 return false; 7 } 8 9 @Override 10 public void onTouchEvent(RecyclerView rv, MotionEvent e) { 11 12 } 13 14 @Override 15 public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { 16 17 } 18 });