事件就是用户与UI界面的交互时所触发的操作。比如点击某一个按钮,会触发一个事件等
1、最长用的按钮事件:OnClickListener
mybutton = (Button)findViewById(R.id.mybutton); mybutton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub ShowMessage("点击了Button按钮"); } });
2、我们还可以自定义KeyEvent,比如
public boolean onKeyDown(int keyCode, KeyEvent event) { /** * 这里构建KeyEvent对象,功能为返回键的功能 * 即我们按任意键都是返回键功能 */ KeyEvent key = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); return super.onKeyDown(keyCode, event); }
3、手机按键的事件处理
Boolean onKeyDown(int keyCode, KeyEvent event):相应按键按下
Boolean onKeyUp(int keyCode, KeyEvent event):相应按键释放
Boolean onKeyMultiple():相应按键重复点击
Boolean onTouchEvent(MotionEvent event):相应触屏事件
package org.hualang.eventtest01; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.Toast; public class EventTest01 extends Activity { /** * 注意,要重写onKeyDown,onKeyUp,onTouchEvent方法 */ private Button mybutton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mybutton = (Button)findViewById(R.id.mybutton); mybutton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub ShowMessage("点击了Button按钮"); } }); } /**按键按下触发的事件*/ public boolean onKeyDown(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: ShowMessage("按下:中键");break; case KeyEvent.KEYCODE_DPAD_UP: ShowMessage("按下:上方向键");break; case KeyEvent.KEYCODE_DPAD_DOWN: ShowMessage("按下:下方向键");break; case KeyEvent.KEYCODE_DPAD_LEFT: ShowMessage("按下:左方向键");break; case KeyEvent.KEYCODE_DPAD_RIGHT: ShowMessage("按下:右方向键");break; } return super.onKeyDown(keyCode, event); } /**按键弹起所触发的事件*/ public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: ShowMessage("弹起:中键"); break; case KeyEvent.KEYCODE_DPAD_DOWN: ShowMessage("弹起:下方向键"); break; case KeyEvent.KEYCODE_DPAD_UP: ShowMessage("弹起:上方向键"); break; case KeyEvent.KEYCODE_DPAD_LEFT: ShowMessage("弹起:左方向键"); break; case KeyEvent.KEYCODE_DPAD_RIGHT: ShowMessage("弹起:右方向键"); break; } return super.onKeyUp(keyCode, event); } /**按键重复点击事件*/ public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return onKeyMultiple(keyCode, repeatCount, event); } /**触屏事件*/ public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); if(action == MotionEvent.ACTION_CANCEL||action == MotionEvent.ACTION_DOWN||action == MotionEvent.ACTION_MOVE) { return false; } //得到触点的位置 String x = String.valueOf(event.getX()); String y = String.valueOf(event.getX()); ShowMessage("触点坐标:(" + x + "," + y +")"); return super.onTouchEvent(event); } /**显示触发事件的信息*/ public void ShowMessage(String str) { Toast toast = Toast.makeText(this, str, Toast.LENGTH_SHORT); toast.show(); } }
运行结果如下: