Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android moving back to first activity on button click

Tags:

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 a button called "home" button. When user clicks on home button in any of the B, C, D activities, application should go back to A activity screen ?

How to simulate "home" button in this case ?

like image 592
cppdev Avatar asked May 05 '10 21:05

cppdev


People also ask

How do I go back to first activity on Android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have given text view, when the user click on text view, it will open new activity.

What is startActivity in Android?

To start an activity, use the method startActivity(intent) . This method is defined on the Context object which Activity extends. The following code demonstrates how you can start another activity via an intent. # Start the activity connect to the # specified class Intent i = new Intent(this, ActivityTwo.


2 Answers

button.setOnClickListener(new View.OnClickListener() {     public void onClick(View v) {         startActivity(new Intent(D.this, A.class));     } }); 

Declare A in your manifest with the android:launchMode="singleTask". This way, when you call startActivity() from your other activies, and A is already running, it will just bring it to the front. Otherwise it'll launch a new instance.

like image 138
synic Avatar answered Sep 16 '22 14:09

synic


The only problem i see using android:launchMode="singleTask" is whenever you minimize app and start app by pressing app icon again then app start from scratch and doesn't acquire its state. so i have opted to use

intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ); 

which will keep only one instance and clear all activities on top of that.

Intent intent = new Intent( context, MyActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ); current_activity.startActivity( intent ); 
like image 45
vivek Avatar answered Sep 16 '22 14:09

vivek