How can I use the Android back button to move back within my app instead of closing my app?

狂风中的少年 提交于 2020-01-11 10:35:09

问题


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?


回答1:


I suspect you call finish() in your OK button onclick listener. Don't do that. finish() removes your activity from activity stack.

Read more here.




回答2:


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

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);
}



回答3:


When you are Ok button r u starting an intent...like

Intent int=new intent(context,B.class); startActivity(int);

then if you are not handling backbutton.

If use default back button...it will goes back to A.

Hope it helps...




回答4:


In my onClick method (in Main Activity) I use the code:

 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.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    //your code here
    //if (keyCode ==
    //...
    //else
    return super.onKeyDown(keyCode, event);
}


来源:https://stackoverflow.com/questions/5406919/how-can-i-use-the-android-back-button-to-move-back-within-my-app-instead-of-clos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!