现在的位置: 首页 > 综合 > 正文

Android初级教程_onKeyDown监听返回键无效

2013年06月16日 ⁄ 综合 ⁄ 共 1480字 ⁄ 字号 评论关闭

当我们的Activity继承了TabActivity,在该类中重写onKeyDown是监听不到返回键的,

具体解决方法如下:

重写dispatchKeyEvent

/** 
  1.  * 退出 
  2.  */  
  3. @Override  
  4. public boolean dispatchKeyEvent(KeyEvent event) {  
  5.     if (event.getKeyCode() == KeyEvent.KEYCODE_BACK  
  6.             && event.getAction() == KeyEvent.ACTION_DOWN  
  7.             && event.getRepeatCount() == 0) {             
  8.         //具体的操作代码   
  9.     }  
  10.     return super.dispatchKeyEvent(event);  
  11. }  
	/**
	 * 退出
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getRepeatCount() == 0) {			
			//具体的操作代码
		}
		return super.dispatchKeyEvent(event);
	}

---------------------------------------------------------------后续2012-8-23-----------------------------------------


如果仅仅是监听某个Activity的后退键,只需要覆写该方法即可.

  1. @Override  
  2. public void onBackPressed() {  
  3.     super.onBackPressed();  
  4. }  
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}


我们可以看看super.onBackPressed()方法默认的实现:

/**  
  1.  * Called when the activity has detected the user's press of the back  
  2.  * key.  The default implementation simply finishes the current activity,  
  3.  * but you can override this to do whatever you want.  
  4.  */  
  5. public void onBackPressed() {  
  6.     finish();  
  7. }  
    /**
     * Called when the activity has detected the user's press of the back
     * key.  The default implementation simply finishes the current activity,
     * but you can override this to do whatever you want.
     */
    public void onBackPressed() {
        finish();
    }

如果想屏蔽后退键只需要把super.onBackPressed()方法注释即可

但是该方法不适用于TabActivity.

抱歉!评论已关闭.