Android fragments navigation and backstack

2019-02-16 19:18发布

问题:

I have a header bar (kinda like menu) and 4 fragments (MAIN, A, B, C) from which the MAIN should be 'main/root' fragment for backstack.

Problem i have is when user via menu goes for example MAIN > A > B > C. If i simply use backstack it will go in reverse order which i don't want. I need back button to go back to MAIN no matter how user navigated to one of those 3.

My current code (which is wrong, it quits app when not in MAIN and current fragment is switched from other non-MAIN fragment) looks like this:

private void SwitchFragment(Fragment pFragment)
{
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.main_fl_fragmentcontainer, pFragment);
    if (_CurrentFragment == _Frag_Main)
        ft.addToBackStack(null);
    ft.commit();

    _CurrentFragment = pFragment;
}

回答1:

Your stack must contains 2 fragments at maximum

Main is visible Main is onBackstack / AorBorC is visible. User click on back ==> Main is visible. User click on back ==> application end

I suppose A / B / C are displayed in the same view so in this case,

When user click on your Menu, you have to check if A/ B / C is currently displayed and replace it by the one selected by the user.

private void displayFragment(Fragment pFragment) {
    Fragment fr = getSupportFragmentManager()
            .findFragmentById(R.id.main_fl_fragmentcontainer);        
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.main_fl_fragmentcontainer, pFragment);
    if (_CurrentFragment == _Frag_Main) {
        ft.addToBackStack(null);
    }
    ft.commit();    
    _CurrentFragment = pFragment;
}

can override OnBackPressed method of your activity.