0

I am using a navigation drawer and fragments to inflate the main activity. However when I press the back button it closes the application which is obvious with fragment setup.

What I want is that when the user clicks the back button they go to the home page fragment if its not currently the view, but if they are on the home page I want the app to close.

How to go around this problem?

dw19
  • 73
  • 2
  • 11

2 Answers2

1

Overriding the back button would be a REALLY BAD idea, as it will hurt more than help.

If you want to add a Fragment that will not be replaced (Your initial "HomePageFragment"), just add this line:

  transaction.addToBackStack(null);

Which will give you something like:

 final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment, fragment, TAG_FRAGMENT);
    transaction.addToBackStack(null);
    transaction.commit();

If you add some other Fragments, don't add them to the back stack.

Waza_Be
  • 39,407
  • 49
  • 186
  • 260
  • 1
    {transaction.addToBackStack(null);} This line of code did it. Thanks man! But when I go from Fragment_2 to HomeFragment, the title of HomeFragment say Title1 is changed to Title2, that is the title of Fragment_2, how to resolve it? – dw19 Feb 01 '14 at 08:53
  • Put your title in the onActivityCreated() // onResume(), depending on what you want of your fragment: getActivity().getActionBar().setTitle("blah") – Waza_Be Feb 01 '14 at 12:13
  • `transaction.addToBackStack("yourTag" or null);` Tag is used for if you want to quickly find your framgent later. PopBackStackImmediate `fragmentManager.popBackStackImmediate("yourTag", 0);` More detail [here](https://developer.android.com/reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String)) – Maxime Jallu Dec 21 '17 at 13:02
-1

You should override the onBackPressed method in the activity class and using that you can determine whether you need to switch back to your home fragment or call super.onBackPressed().

Anid Monsur
  • 4,538
  • 1
  • 17
  • 24