I have a project in Android studio with several activities, in which I want the moment when I press the back button of the navigation bar to return to the main screen of my project.
Thank you in advance
I have a project in Android studio with several activities, in which I want the moment when I press the back button of the navigation bar to return to the main screen of my project.
Thank you in advance
If you are opening activities from other activities (in addition to the MainActivity
) then what you have to do is finish those activities with finish()
right after the call to startActivity
.
That way any activity that is no longer visible will be dead (except for MainActivity).
From my absolute novatez, I imagine that you could overwrite the onBackPressed method and then do an intent to the Activity that you want:
@Override
public void onBackPressed() {
//Aquí tu Intent...
}
Hello, you should try writing the @back method with an attempt to check if the desired activity already exists in the stack, in this way you would avoid creating unnecessary instances, the flags you can use are Intent.FLAG_ACTIVITY_CLEAR_TOP that would clean the stack later to do the intent and Intent.FLAG_ACTIVITY_SINGLE_TOP that checks if there is activity on the stack
@Override
public void onBackPressed() {
Intent intent = new Intent().setClass(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
Simply overwrite the onBackPressed method of the activity
@Override
public void onBackPressed() {
startActivity(new Intent(this,MainActivity.class));
}