Search code examples
androidandroid-fragmentsslidingdrawer

Back Button Handling in SlidingDrawer for mulitple fragment?


I have searched for this solution many times but couldn't find what i want.I have a slidingdrawer in my app.Now the options in the drawer is:

1.Home
2.Friends
3.Groups and many more

Now for every option i have many fragments.Like for Home and Friends option the fragments goes like
Home->fragment1->fragment2->fragment3
Friends->fragment4->fragment5

Case 1: Now when i go to frament1 from Home and then to frament2 and again clicking Friends and then go to fragment4.Now when i press Back Button it is also showing the fragments of the Home .But i want to restrict the Back button to show only it's options fragment i.e it won't show the fragment of Home using Back button when i am in Friends.How to do it in slidingdrawer activity and what to do in the corresponding fragments??

Case 2: What i see in my app is that when i was pressing Back button sometimes i could see my fragment over another fragment i.e i could see two fragments mixed up.Why didn't it replace the fragment fully??

Now what i implemented in my SlidingDrawer:

Fragment fragment = new HomeFragment(); // i have this initialized previously for every item of listview
FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();
        fragmentManager.beginTransaction().addToBackStack(null);


and What i did to go to another fragment from this fragment.For example: in HomeFragment to goto another fragment i did:

FragmentManager fragmentManager = getFragmentManager();
                Fragment fragment = new FriendsStatusFragment();
                fragmentManager.beginTransaction().replace(R.id.frame_container,fragment).commit();


In some Fragment this works nice but sometimes the problem of case 2 occurs and the back button is not working according to my desire mentioned in case 1 .Can anyone Show me Path??Thanks in advance...


Solution

  • To make sure you don't return to fragments within Home when you're in Friends, call popBackStack before you load in the Friends fragment (when you switch Options) to clear all the fragments in the back stack.

    FragmentManager fragmentManager = getFragmentManager();
    Fragment fragment = new FriendsStatusFragment();
    popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    fragmentManager.beginTransaction().replace(R.id.frame_container,fragment).commit();