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.