2

I have my MainActivity which has 6 fragments in the Navigation Drawer. Now, whenever I am in any of the 6 fragments and if I press back button, my app is exiting. I want to exit only from the 1st fragment. If I am in other fragments, then if I press back, I want it to come to the 1st fragment and from there if I press back again, then I want to exit. I have to replace the fragments to the 1st fragment when it is not in the 1st position. I know that. But how exactly can I implement the whole in onBackPressed ? Please help !! Thanks in advance.

Anupam
  • 2,845
  • 2
  • 16
  • 30
  • this http://stackoverflow.com/questions/5448653/how-to-implement-onbackpressed-in-android-fragments mays help you – Linh May 23 '16 at 08:46
  • Refer the following links to goback your fragment, http://stackoverflow.com/questions/9702216/get-the-latest-fragment-in-backstack and http://stackoverflow.com/questions/7919681/how-to-determine-fragment-restored-from-backstack – Ganesh Krishnamoorthy May 23 '16 at 08:47

2 Answers2

1

override the onBackPress method and add this code;

public void onBackPressed(){
        int count = getFragmentManager().getBackStackEntryCount(); // if stack count is 0, it means no fragment left to pop back stack
        if (count = 0) {
            finish();
        } 
    }
Rashid
  • 1,700
  • 1
  • 23
  • 56
1

You can get the fragment name with the instance and we can check weather it is in home fragment or not. Paste this code in the onBackPressed method in main activity class.

Fragment  f = getSupportFragmentManager().findFragmentById(R.id.frame_container);

            /**
             * Compare the instances based on fragment name to change the action bar
             */

            if (f instanceof HomeFragment) {
                finish();
                System.exit(0);
            } else {
                super.onBackPressed();
            }
Jeevanandhan
  • 1,073
  • 10
  • 18