欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-24 14:26:01
...

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

具体解决方法如下:

重写dispatchKeyEvent


	/**
	 * 退出
	 */
	@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的后退键,只需要覆写该方法即可.

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}


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

    /**
     * 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.


欢迎转载:http://blog.csdn.net/johnny901114/article/details/7822878