How to make an activity stop, rather then be destroyed, from the BACK key?

前端 未结 7 1319
心在旅途
心在旅途 2020-12-15 07:02

Right now an activity gets destroyed when the BACK key is pressed. How can I make it just stop ( i.e. keep all the variables, etc. alive ), rather then be destroyed?

7条回答
  •  情歌与酒
    2020-12-15 07:44

    I have managed to work out exactly what you want: switch between 2 activities using Back button and keep them all not to be destroyed!

    For example: you have 2 activities A & B. A will be started first, then A calls B. When B is loaded, user press Back button and switches back to activity A from B. From now B should not be destroyed and just goes to background, and when user starts activity B from A again, activity B will be brought to foreground, instead of being re-created again or created new instance!

    How to implement this:

    1. Override onBackPressed() of activity B:

    @Override
    public void onBackPressed() {
        Intent backIntent = new Intent(this, ActivityA.class);
        backIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(backIntent);
    }
    

    2. On activity A, call activity B:

    public void callActivityB() {
        Intent toBintent = new Intent(this, ActivityB.class);
        toBIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(toBintent);
    }
    

    remember to add flag: Intent.FLAG_ACTIVITY_REORDER_TO_FRONT when you call A&B.

提交回复
热议问题