mike5v mike5v - 1 month ago 12
Android Question

Back button in fragment

I have a navigation drawer and 8 fragment (one of which is my "main fragment"), selecting the item I select the fragment corresponding content in MainActiviy.
When I am in one of the fragment and I press the back button the application closes, while I would like it closed only when it is in a specific fragment ("main fragment"), while when I am in the other must return to the "main fragment"
How can I do this?
Thanks in advance

Answer
         FragmentManager fragmentManager = getFragmentManager();

            Fragment detail2 = new FragmentName();

            fragmentManager.beginTransaction().replace(R.id.content_frame, detail2).addToBackStack("tag").commit();

addtobackstack("tag") when you starting the fragment like the above code. And add the below code in your activity

 @Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}