简体   繁体   中英

Change back button behavior

I have this activities structure in my android app (the arrow means that i'm pressing button that opens the next activity/fragment):

Activity A -> Fragment A -> Fragment B -> Activity B -> Fragment B

I want that when i press back button on last Fragment B it goes to Activity A, instead of Activity B. Is it possible?

It works only if i follow this path on my app: Activity A -> Fragment A -> Fragment B

How to do that?

This actually happens in your current code. If you are at the last Fragment B (in Activity B) and pressed back, It takes you back to Activity A but with Fragment B loaded .. which is the state you navigated from when you went to Activity B.

To resolve this, you can use startActivityForResult and onActivityResult in Activity A. And when the onActivityResult is called, hide Fragment B and show Fragment A.

You can either use finish() in the activity that you don't want to go back to ( finish() kills the activity) or implement your own method to override the default. Hope this helps.

@Override
public void onBackPressed() {
    // New code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM