Return back to MainActivity from another activity

前端 未结 8 1001
予麋鹿
予麋鹿 2020-12-08 03:01

The MainActivity contains some buttons. Each button opens a new activity via an intent. These activities then have a button to return to the MainActivity<

相关标签:
8条回答
  • 2020-12-08 03:14

    I highly recommend reading the docs on the Intent.FLAG_ACTIVITY_CLEAR_TOP flag. Using it will not necessarily go back all the way to the first (main) activity. The flag will only remove all existing activities up to the activity class given in the Intent. This is explained well in the docs:

    For example, consider a task consisting of the activities: A, B, C, D.
    If D calls startActivity() with an Intent that resolves to the component of
    activity B, then C and D will be finished and B receive the given Intent, 
    resulting in the stack now being: A, B.
    

    Note that the activity can set to be moved to the foreground (i.e., clearing all other activities on top of it), and then also being relaunched, or only get onNewIntent() method called.

    Source

    0 讨论(0)
  • 2020-12-08 03:23

    use

    Intent returnBtn = new Intent(getApplicationContext(),
                        MainActivity.class);
    
    startActivity(returnBtn);
    

    make the main activity's launchmode to singleTask in Android Manifest if you don't want to create new one every time.

    android:launchMode="singleTask" 
    
    0 讨论(0)
提交回复
热议问题