Android - onBackPressed() 不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3558385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android - onBackPressed() not working
提问by Donal Rafferty
I have an application building against Android 2.1 and I want to override the back button.
我有一个针对 Android 2.1 构建的应用程序,我想覆盖后退按钮。
I have followed the example here:
我已经按照这里的例子:
http://android-developers.blogspot.com/2009_12_01_archive.html
http://android-developers.blogspot.com/2009_12_01_archive.html
And my code is as follows:
我的代码如下:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
Log.d("CDA", "onKeyDown Called");
onBackPressed();
}
return true;
}
@Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
return;
}
It works on pre 2.x devices but doesn't work on a Hero with 2.1 update-1 and a Nexus One with 2.2.
它适用于 2.x 之前的设备,但不适用于带有 2.1 update-1 的 Hero 和带有 2.2 的 Nexus One。
Is there somwthing I am missing from the example? Or can anyone point out why it isn't working?
我在这个例子中遗漏了什么吗?或者任何人都可以指出为什么它不起作用?
I dont even get the button pressed in the logcat.
我什至没有在 logcat 中按下按钮。
回答by Jorgesys
Are you using onKeyUp()?
你在使用onKeyUp()吗?
Use just onKeyDown()in Android 1.x or onBackPressed()in Android 2.x
在 Android 1.x 中只使用onKeyDown()或在 Android 2.x 中使用onBackPressed()
回答by gary
Some quick searching suggests you should place the Back intercept during onKeyUp(): http://developer.android.com/sdk/android-2.0.html. It's worth a try. The following code is directly from the site:
一些快速搜索建议您应该在 onKeyUp() 期间放置 Back 拦截:http: //developer.android.com/sdk/android-2.0.html。这值得一试。以下代码直接来自网站:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
event.startTracking();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
&& !event.isCanceled()) {
// *** DO ACTION HERE ***
return true;
}
return super.onKeyUp(keyCode, event);
}
回答by ashakirov
You should call parent constructors.
您应该调用父构造函数。
In onKeyDown()
method call
在onKeyDown()
方法调用中
super.onKeyDown();
and in onBackPressed()
并在 onBackPressed()
super.onBackPressed();