Android提供的事件處理機制分為兩類:一是基於監聽的事件處理;二是基於回調的事件處理。對於基於監聽的事件處理,主要的做法是為Android介面組件綁定特定的事件監聽器。對於基於回調的事件處理,主要是重寫Android組件特定的回呼函數或重寫Activity的回呼函數。
基於監聽的事件處理,在前面的文章中我們已經用過,比如為Button設定點擊監聽器。本文我們主要來看基於回調的事件處理。
我們只需要看主Activity實現檔案,其內容如下:
package com.liuhaoyu; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.MotionEvent; import android.widget.Toast; public class MainActivity extends Activity{ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override publicboolean onTouchEvent(MotionEvent event) { //TODO Auto-generated method stub Toast.makeText(MainActivity.this,"onTouchEvent(): " + "(" + event.getX() + "," +event.getY() + ")", Toast.LENGTH_SHORT).show(); if(event.getAction()== MotionEvent.ACTION_MOVE) Toast.makeText(MainActivity.this,"onTouchEvent(): touch move", Toast.LENGTH_SHORT).show(); returnsuper.onTouchEvent(event); } @Override publicboolean onKeyDown(int keyCode, KeyEvent event) { //TODO Auto-generated method stub Toast.makeText(MainActivity.this,"onKeyDown(): KeyCode = " + keyCode, Toast.LENGTH_SHORT).show(); returnsuper.onKeyDown(keyCode, event); } @Override publicboolean onKeyUp(int keyCode, KeyEvent event) { //TODO Auto-generated method stub Toast.makeText(MainActivity.this,"onKeyUp(): KeyCode = " + keyCode, Toast.LENGTH_SHORT).show(); returnsuper.onKeyUp(keyCode, event); } } package com.liuhaoyu; import android.app.Activity;import android.os.Bundle;import android.view.KeyEvent;import android.view.MotionEvent;import android.widget.Toast; public class MainActivity extends Activity{ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override publicboolean onTouchEvent(MotionEvent event) { //TODO Auto-generated method stub Toast.makeText(MainActivity.this,"onTouchEvent(): " + "(" + event.getX() + "," +event.getY() + ")", Toast.LENGTH_SHORT).show(); if(event.getAction()== MotionEvent.ACTION_MOVE) Toast.makeText(MainActivity.this,"onTouchEvent(): touch move", Toast.LENGTH_SHORT).show(); returnsuper.onTouchEvent(event); } @Override publicboolean onKeyDown(int keyCode, KeyEvent event) { //TODO Auto-generated method stub Toast.makeText(MainActivity.this,"onKeyDown(): KeyCode = " + keyCode, Toast.LENGTH_SHORT).show(); returnsuper.onKeyDown(keyCode, event); } @Override publicboolean onKeyUp(int keyCode, KeyEvent event) { //TODO Auto-generated method stub Toast.makeText(MainActivity.this,"onKeyUp(): KeyCode = " + keyCode, Toast.LENGTH_SHORT).show(); returnsuper.onKeyUp(keyCode, event); }}
這個例子響應按鍵事件和觸控螢幕事件。
對於按鍵事件,我們重寫了onKeyDown()和onKeyUp()函數。
對於觸控螢幕事件,我們重寫了onTouchEvent()函數。
基於回調事件處理函數,有一個boolean類型的傳回值,這個傳回值用來表明該事件處理函數能否完成對該事件的處理,如果能完成,傳回值為true,事件就是會繼續傳遞下去。如果不能完成,傳回值為false,表明沒有完成對事件的處理,事件還會繼續傳遞下去。