java 如何使用 Android 后退按钮在我的应用程序中返回而不是关闭我的应用程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5406919/
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
How can I use the Android back button to move back within my app instead of closing my app?
提问by Siva K
My app has three activities, A, B and C. I am moving from A to B through an OK button, and I want to move back from B to A by using the default back button of Android devices. When I press the button, though, the entire app gets closed. How can I get around this problem?
我的应用程序有三个活动,A、B 和 C。我通过 OK 按钮从 A 移动到 B,我想使用 Android 设备的默认后退按钮从 B 移动回 A。但是,当我按下按钮时,整个应用程序都会关闭。我怎样才能解决这个问题?
回答by Vladimir Ivanov
回答by olamotte
why start your activity for result ? when you press the backbutton, the result is set to RESULT_CANCELED form the B activity, so it crashes if you don't handle the resultcode...
为什么要开始你的活动以获得结果?当您按下后退按钮时,B 活动将结果设置为 RESULT_CANCELED,因此如果您不处理结果代码,它就会崩溃...
you can handle the backpress like this
你可以像这样处理背压
private static final int NONE = -1;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
setResult(NONE, intent);
finish();
return super.onKeyDown(keyCode, event);
}
回答by Udaykiran
When you are Ok button r u starting an intent...like
当你确定按钮 ru 开始一个意图......就像
Intent int=new intent(context,B.class); startActivity(int);
Intent int=new intent(context,B.class); 开始活动(INT);
then if you are not handling backbutton.
那么如果你不处理后退按钮。
If use default back button...it will goes back to A.
如果使用默认的后退按钮......它会回到A。
Hope it helps...
希望能帮助到你...
回答by firefox1986
In my onClick method (in Main Activity) I use the code:
在我的 onClick 方法(在 Main Activity 中)中,我使用了以下代码:
Intent intent = new Intent(context, SecondActivity.class);
context.startActivityForResult(intent, SecondActivity.SECONDACTIVITY_REQUEST);
In the manifest I've got:
在清单中我有:
<activity android:name=".SecondActivity" android:screenOrientation="landscape" android:launchMode="standard"></activity>
This works for me without any other settings that I can see. What events are you responding to?
这对我有用,没有我可以看到的任何其他设置。你在回应什么事件?
Note that you can also go back an activity, in code like this:
请注意,您还可以使用以下代码返回活动:
super.setResult(Activity.RESULT_OK);
super.finish();
Edit... Make sure you're not swallowing the event in the Main Activitys onKeyDown event.
编辑... 确保您没有吞下 Main Activitys onKeyDown 事件中的事件。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//your code here
//if (keyCode ==
//...
//else
return super.onKeyDown(keyCode, event);
}