在android平台上捕获Back键事件,主要用来处理返回的相关逻辑,下列几种方法都可以捕获,如下所示:
1、获取按钮按下事件,兼容android 1.0到android 2.1,重写onKeyDown()即可
1 @Override 2 public boolean onKeyDown(int keyCode, KeyEvent event) 3 { 4 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) 5 { 6 // your code 7 return true;// true 事件不继续传递, false 事件继续传递 8 } 9 else 10 { 11 return super.onKeyDown(keyCode, event); 12 } 13 }
2、android 2.0后,捕获Back键的按下事件,重写onBackPressed()即可
1 @Override 2 public void onBackPressed() 3 { 4 // your code 5 return; 6 }
3、在dispatchKeyEvent()中捕获处理
1 @Override 2 public boolean dispatchKeyEvent(KeyEvent event) 3 { 4 if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK) 5 { 6 // your code 7 return true; 8 } 9 else 10 { 11 return super.dispatchKeyEvent(event); 12 } 13 }