歡迎使用CSDN-markdown編輯器,csdn-markdown
Android手勢操作
一盞燈, 一片昏黃; 一簡書, 一杯淡茶。 守著那一份淡定, 品讀屬於自己的寂寞。 保持淡定, 才能欣賞到最美麗的風景! 保持淡定, 人生從此不再寂寞。
前言
利用手勢操作在現在的APP中越來越普及,大多數時候使用Fling,Scroll等Gesture能大幅度提高使用者的操作體驗,特別是大屏手機返回鍵程越來越大的現狀下。
在Android系統下,手勢識別是通過GestureDetector.OnGestureListener介面實現的,不過官方的文檔可能覺得這部分太基礎和簡單了,所以官方的API文檔中對手勢的講解描述的都很簡單,API Demo中也沒有提供一個清楚的例子,所以自己總結一下,其中還是涉及不少的基礎知識和一些官方文檔中說明不清的地方,如果不能好好掌握這些基礎知識,做起事情來難免要吃一些苦頭。言歸正傳,下面我們開始:
基礎知識
我們先來明確一些概念,首先,Android的事件處理機制是基於Listener(監聽器)來實現的,比我們今天所說的觸控螢幕相關的事件,就是通 過onTouchListener。其次,所有View的子類都可以通過setOnTouchListener()、 setOnKeyListener()等方法來添加對某一類事件的監聽器。第三,Listener一般會以Interface(介面)的方式來提供,其中 包含一個或多個abstract(抽象)方法,我們需要實現這些方法來完成onTouch()、onKey()等等的操作。這樣,當我們給某個view設定了事件Listener,並實現了其中的抽象方法以後,程式便可以在特定的事件被dispatch到該view的時候,通過callbakc函數給予適當的響應。
這篇文章簡單介紹了事件觸發的過程:Android事件分發圖解
實作
我們現在實作一個使用手勢的例子。
我們給RelativeView的執行個體my_view設定了一個onTouchListener,因為GestureTest類實現了OnTouchListener 介面,所以簡單的給一個this作為參數即可。onTouch方法則是實現了OnTouchListener中的抽象方法,我們只要在這裡添加邏輯代碼即 可在使用者觸控螢幕幕時做出響應,
public class MainActivity extends ActionBarActivity implements View.OnTouchListener,GestureDetector.OnGestureListener{
GestureDetector gestureDetector = null;
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gestureDetector = new GestureDetector(this); gestureDetector.setIsLongpressEnabled(true); View v = findViewById(R.id.my_view); v.setOnTouchListener(this);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item);}@Overridepublic boolean onTouch(View view, MotionEvent motionEvent) { Log.i("HYY","onTouch present"); return gestureDetector.onTouchEvent(motionEvent);}@Overridepublic boolean onDown(MotionEvent motionEvent) { Log.i("HYY","onDown present"); return true;}@Overridepublic void onShowPress(MotionEvent motionEvent) { Log.i("HYY","onShowPress present");}@Overridepublic boolean onSingleTapUp(MotionEvent motionEvent) { Log.i("HYY","onSingleTapUp present"); return false;}@Overridepublic boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent2, float v, float v2) { Log.i("HYY","onScroll present"); return false;}@Overridepublic void onLongPress(MotionEvent motionEvent) { Log.i("HYY","onLongPress present");}@Overridepublic boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent2, float v, float v2) { Log.i("HYY","onFling present"); return false;}
}
這裡有一點需要特別注意:要觸發onScroll和onFling,必須讓監聽器的onDown的傳回值設為true