简体   繁体   中英

Android: how to quit an activity without closing it when click on back button?

I have a subActivity that can be open from my mainActivity.

For some reasons, when the user clicks on the back button go back to my mainActivity, I want my subActivity to remain open in background in order to be able to come back for later.

Questions:

  • how to avoid to close the subActivity when the user clicks back ?
  • how to come back to the mainActivity without restarting it ?
  • how to come back later to my opened activity without re-creating it completely ? (just want to bring it to front)

Thanks !

On you subActivity onBackPressed() add this

@Override
public void onBackPressed() {
     Intent i = new Intent(SubActivity.this, MainActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

    startActivity(i);
}

on mainActivity :

  private void openSubActivity() {        

        Intent intent = new Intent(MainActivity.this,SubActivity.class);
       intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);

    }

override onBackPressed() and remove super from it then try opening the activity which you want to open from there for ex-

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

and with the help of different activity launch modes you can achieve it

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