Determine backstack fragment empty state in android

android, android-activity, android-fragments

Solution

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();
    }
}

Problem

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(); ```

Original source