手勢檢測GestureDetector,gesturedetector
由於在onTouchEvent中判斷使用者手勢的真實想法很不容易,因此Android提供了GestureDetector檢測器來協助我們識別手勢。藉助於GestureDetector,可以在大多數場合下辨別出常用的幾個手勢事件,如點擊、長按、翻頁等等。下面是GestureDetector的相關方法:
建構函式 : GestureDetector(Context context, OnGestureListener listener)
監聽器類名 : OnGestureListener
設定監聽器的方法,先給指定控制項註冊觸摸監聽器,然後在觸摸方法onTouch中由GestureDetector接管觸摸事件 :
private ScrollTextView tv_rough; private GestureDetector mGesture; tv_rough = (ScrollTextView) findViewById(R.id.tv_rough); tv_rough.setOnTouchListener(this); mGesture = new GestureDetector(this, this); @Override public boolean onTouch(View v, MotionEvent event) { return mGesture.onTouchEvent(event); }
另外,也可在當前視圖或當前Activity中重寫onTouchEvent方法,在該方法中由GestureDetector接管觸摸事件。
監聽器需要重寫的方法 :
onDown : 在使用者按下時調用
onShowPress : 已按下但還未滑動或鬆開時調用,通常用於pressed狀態時的高亮顯示
onSingleTapUp : 在使用者輕點一下再彈起時調用,通常用於點擊事件
onScroll : 在使用者滑動過程中調用
onLongPress : 在使用者長按時調用,通常用於長按事件
onFling : 在使用者飛快掠出一段距離時調用,通常用於翻頁事件