简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM