2
votes

Basically when BACK button is pressed on the phone, I want to prevent a specific activity to return to its previous one in android.

Specifically, I have login and sign up screens, both start a new activity called HomeScreen when successful login/signup occurs. Once HomeScreen is started, I want to prevent the users to be able to return login or sign up screens with pressing BACK key also I want them to be able to navigate between fragments in HomeScreen e.g They can navigate to fragments like share,communicate etc.

I thought of using finish() method on backKey pressed but that would exit an application and I don't want that too.

3
Just finish activity that launches HomeScreen activity, so it becomes first in stackRoman Kolomenskii

3 Answers

1
votes

You can try :

public void onBackPressed() {

   if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
        getSupportFragmentManager().popBackStack();
   } else {
        finish();
   }
}

Hope this helps.

1
votes

Call finish() where you start the HomeScreen Intent :

Intent intent = new Intent(this, HomeScreen.class);
startActivity(intent);
finish();
0
votes

Lets say this is the flow of your Activity

SplashActivity----->HomeScreenActivity

1) Remove SplashActivity from BackStack

SplashActivity.java

Intent intent = new Intent(this, HomeScreenActivity.class);
startActivity(intent);
finish();

2) Override onBackPressed() in the HomeScreenActivity

Don't call super.onBackPressed() when you override this method because default implementation calls finish() method internally.

HomeScreenActivity.java

public void onBackPressed() {
    //super.onBackPressed();    <-- Dont call this 

   /* Your logic to navigate between fragments goes here */
}