简体   繁体   中英

Navigation drawer with fragment and on back pressed

I have a navigation drawer with only one activity and several fragments. My main fragment is really heavy to load so I try to keep it in memory because if I don't do it the drawer will be laggy when I use it.

To do so I have a layout like this :

<RelativeLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</RelativeLayout>

<fragment
    android:id="@+id/main_fragment"
    android:name=".MainFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

They they the same place but in the code I replace the fragment layout with lighter fragment and show/hide the main fragment. This is a showFragment method to is called when I click on the item in the drawer.

case 0: //Light Fragment
    fragment = getSupportFragmentManager().findFragmentByTag("light");
    if (fragment == null) {
        fragment = ProfileFragment.newInstance();
    }
    getSupportFragmentManager().beginTransaction().hide(getSupportFragmentManager().findFragmentById(R.id.main_fragment)).commit();
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment, "light").addToBackStack(null).commit();
break;
case 1: //Heavy Frag
    if (getActiveFragment() != null) {
        getSupportFragmentManager().beginTransaction().remove(getActiveFragment()).commit();
    }
    getSupportFragmentManager().beginTransaction().show(getSupportFragmentManager().findFragmentById(R.id.main_fragment)).addToBackStack(null).commit();
break;

Which works fine except when I push the back button. I try many implementation of the onBackPressed but I always end up with either the main fragment showing when it should be hidden (So 2 fragment in top of each other) and the main fragment simply doesn't show.

Bonus question: Is that the correct way of doing thing ? I mean to avoid the drawer to lag or should i completely change my implementation?

Thanks.

Well, this should be more of a comment but since I cannot comment, I have to answer.

The reason could be that the fragments are not going into the backstack properly or in the order as they should.

I once created a project wherein I used Navigation Drawer with fragments. If I understand you correctly, what you want is to go to the last open fragment.

Try using the following code: Put it in onBackPressed()

    @Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
    this.finish();
} else {
    getFragmentManager().popBackStack();
}
}

Essentially, you are popping the last fragment that was added to the backstack.

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