My application structure look like:
SplashActivity -> MainActivity -> (switching between many fragments)
What I expect: finish application from main activity when fragment back stack count is zero. Here is my try:
In SplashAcitivty
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().getBooleanExtra("exit", false)) {
finish();
}
}
In MainActivity:
@Override
public void onBackPressed() {
// I need to implement this method
if( backstackCount() == 0){
Intent intent = new Intent(this, SplashActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(SplashActivity.EXIT_KEY, true);
startActivity(intent);
}else{
super.onBackPressed();
}
}
So, please tell me how can I determine the back stack when it 's empty? Because I use SlideMenu
library, all of my fragments switch many times, and they are added to back stack when switching. Look like this one:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();
Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.
Use getBackStackEntryCount() to get count. If it is zero, means nothing in backstack. Note: FragmentManager class was deprecated in API level P. Use the Support Library FragmentManager for consistent behavior across all devices and access to Lifecycle.
Various Android system operations can affect the state of your fragment. To ensure the user's state is saved, the Android framework automatically saves and restores the fragments and the back stack. Therefore, you need to ensure that any data in your fragment is saved and restored as well.
Since you want only one back stack entry per Fragment , make the back state name the Fragment's class name (via getClass(). getName() ). Then when replacing a Fragment , use the popBackStackImmediate() method. If it returns true, it means there is an instance of the Fragment in the back stack.
Here is my code. It works fine for me:
@Override
public void onBackPressed() {
int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
if (backStackEntryCount == 0) {
goBack(); // write your code to switch between fragments.
} else {
super.onBackPressed();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With