Handling fragment back stack with Navigation Drawer
Asked Answered
S

4

17

I am implementing navigation drawer and works well. So i am calling fragment on navigation drawer click and it is also working and further more i am calling another fragment from Home page fragment and maintain the back stack for every fragment but the problem is back press from the child fragment i can't go to Home page fragment and just exited from application. I don't want this. What i want Click on

Navigation Drawer->HomePageFragment->AnotherChild Fragment(On List Item click of HomePageFragment)

but on back pressed without going to Homepage fragment its directly exit with application. Here is my code: (In Fragment Activity with Navigation Drawer)

class SlideitemListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {

        updateDisplay(position);
    }

}

private void updateDisplay(int position) {
    Fragment fragment = null;
    switch (position) {
    case 0:
        fragment = new ScheduleFragment();
        break;
    case 1:
        fragment = new Result_Fragment();
        break;
    case 2:
        fragment = new Live_Match_Fragment();
        break;
    case 3:
        // fragment = new Live_Match_Fragment();
        break;

    case 4:
        fragment = new Team_Fragment();
        break;
    default:
        break;
    }

    if (fragment != null) {

        fragmentManager = getFragmentManager();
        fragmentManager.popBackStackImmediate("0", 0);
        int count = fragmentManager.getBackStackEntryCount();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        fragmentTransaction.replace(R.id.frame_container, fragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .addToBackStack(String.valueOf(count)).commit();
        Log.e("Count in Activiy", ""+count);

        // update selected item and title, then close the drawer
        setTitle(menutitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }

}

Now in BackPressed() in FragmentActivity.

@Override
public void onBackPressed() {
    if (fragmentManager.getBackStackEntryCount() <= 1) {
        finish();

        return;
    }
    super.onBackPressed();
}

Now calling another child fragment from HomePage fragment on Listview item click.

 team_lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            TeamDetailFragment myDetailFragment = new TeamDetailFragment();
            FragmentManager fragmentManager = getFragmentManager();
            int count = fragmentManager.getBackStackEntryCount();
            Log.e("Count in Fragment", "" + count);
            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();
            fragmentTransaction
                    .replace(R.id.frame_container, myDetailFragment)
                    .setTransition(
                            FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    .addToBackStack(String.valueOf(count)).commit();

        }
    });

So anybody knows then help me. Help will be appreciate.

Sinuation answered 25/4, 2014 at 12:30 Comment(8)
Why have you written this line fragmentManager.popBackStackImmediate("0", 0); ? You are immediately poping the previous fragment after adding new one.Grackle
This is implementing because when click on navigation drawer, this will clear the memory of previous fragments and will not go back to them on "back" pressed.Sinuation
Then why have you asked to manage backpressed ?Grackle
the problem is back press from the child fragment i can't go to Home page fragment explain this !!!Grackle
while i am going from child fragment to home fragment then directly exit from activity because i have finish activity in splash screen.Sinuation
From which child fragment you want to switch to home ?Grackle
That means when i am in child fragment and on back presssed i want to go to Home fragment and after that again back press i want to exit from application.Sinuation
I created a sample application on GitHub to solve your problem. Download Fragment Back Stack applicationBarlow
P
3

There is an issue with nested fragments in android https://code.google.com/p/android/issues/detail?id=40323

Android doesn't handle back press well if transactions were in nested fragments. To surpass this i am using the following fix inside My Activity

@Override
public void onBackPressed() {
    // If the fragment exists and has some back-stack entry
    if (myFragment != null && myFragment.getChildFragmentManager().getBackStackEntryCount() > 0) {
        // Get the fragment fragment manager - and pop the backstack
        myFragment.getChildFragmentManager().popBackStack();
    }
    // Else, nothing in the direct fragment back stack
    else {
        // Let super handle the back press
        super.onBackPressed();
    }
}
Phonetician answered 26/2, 2015 at 11:21 Comment(0)
R
2

I've solved in the following way:

1st solution

@Override
public void onBackPressed() {
    FragmentManager fragmentManager = getFragmentManager();
    int backCount = fragmentManager.getBackStackEntryCount();

    if(backCount > 1) {
        super.onBackPressed();
    } else {
        finish();
    }
}

2nd solution

@Override
public void onBackStackChanged() {
    FragmentManager fragmentManager = getFragmentManager();
    int backCount = fragmentManager.getBackStackEntryCount();

    if(backCount == 0) {
        finish();
    }
}

These allow you to exploit the Android stack when you replace your fragment:

FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, yourFragment)
    .addToBackStack(null).commit();
Risible answered 25/8, 2015 at 9:5 Comment(0)
T
0

When you press back button inside your fragment onBackPressed() method of your activity will be called if you have declared that..So handling back button for fragments within navigation drawer can be one in this way..

MainActvity

     public static boolean isMainActivityShown ;
     public static boolean isFragment1Shown=false ;
     public static boolean isFragment2Shown=false ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isMainActivityShown=true  //inside onCreate method put isMainActivityShown true
. 
. 
.


 {
               Fragment currentFragment = new Fragment1();
               isMainActivityShown=false;   //when moving to fragment1 
               isFragment1Shown=true;
               frgManager = getFragmentManager();
               frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
                                        .commit();
 }
.
.
}



  @Override
        public void onBackPressed() {

            if(isMainActivityShown)
            {
                finish();
            }
            else if(isFragment1Shown)
            {
               //write the code to handle back button when you are in Fragment1
            }
           else if(isFragment2Shown)
            {  //When you are in Fragment 2 pressing back button will move to fragment1
                Fragment currentFragment = new Fragment1();
                isFragment2Shown=false;
                isFragment1Shown=true;

                FragmentManager frgManager;
                frgManager = getFragmentManager();
                frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
                        .commit();
            }

            }

Fragment1

Fragment currentFragment = new Fragment2();
MainActivity.isFragment1Shown=false;
MainActivity.isFragment2Shown=true;
frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, currentFragment)
                                    .commit();
Tupi answered 1/11, 2014 at 10:59 Comment(0)
C
0

Now you can replace finish() for fragmentManager.popBackStack(), method of android.support.v4.app.FragmentManager

Cann answered 21/9, 2016 at 18:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.