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<
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
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"