Android moving back to first activity on button click

后端 未结 6 2191
情歌与酒
情歌与酒 2020-12-03 07:14

I am writing a application where I am dealing with 4 activities, let\'s say A, B, C & D. Activity A invokes B, B invokes C, C invokes D. On each of the activity, I have

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 07:47

    First of all I can't believe Android does not have an easy equivalent of iOS poptorootviewcontroller.

    The problem with using an intent and startactivity is that as far as I know it will recreate the root activity which is a problem if for example it is using an asynchronous network request to load data and layout the interface. This may have unpleasant visual effects.

    Here is a creative solution I have used in my friendfolder project:

    Create a global boolean: public boolean myBool = true; Do this in MyApplication class and register the class in the manifest:

    Activity A is the root, do this in onResume:

    if(((MyApplication) this.getApplication()).myBool == false) {
            if(isTaskRoot()) {
    
                ((MyApplication) this.getApplication()).myBool = true;
            } else {
                finish();
            }
        }
    

    In every activity that will go on top of Activity A put this code in:

    @Override
    public void onResume() {
        super.onResume();
    
        if(((MyApplication) this.getApplication()).myBool == false) {
                finish();
        }
    
    }
    
    @Override
    public boolean onSupportNavigateUp(){
    
        ((MyApplication) this.getApplication()).myBool = false;
    
        finish();
    
        return true;
    }
    

    You can even put this in activity A as well if you are stacking other instances of A on top of the root A. onSupportNavigateUp is for the up button. Substitute this method for another if using your own button.

    Now when you have some activities stacked on top of A and you press the up button the top activity will finish and the onresume will be called by the system on the activity below in the stack and it will finish. This will work in a chain all the way back to the root A.

提交回复
热议问题