I am using the new NavigationView in order to show a navigation menu with the Android Design Support Library. I am also using a FrameLayout into the DrawerLayout to replace fragments into it.
The problem occurs when I change between fragments. I mean, when I use the NavigationView to click on another Fragment and come back again to the first one, the view has been just "cleaned" (f.e. content from ViewPagers Tabs just disappear). I don't know how to "refresh" the FrameLayout or if I have to reuse the Fragments instead of using transaction.replace().
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" />
<include layout="@layout/toolbar" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/menu_drawer" />
</android.support.v4.widget.DrawerLayout>
I also use this method to switch between fragments into the FrameLayout.
private void displayFragment(int position) {
Fragment fragment = null;
String title = "";
switch (position) {
case 0:
fragment = new FragmentA();
title = getString(R.string.fragment_a);
break;
case 1:
fragment = new FragmentB();
title = getString(R.string.fragment_b);
break;
case 2:
fragment = new FragmentC();
title = getString(R.string.fragment_c);
break;
default:
fragment = new HomeFragment();
title = getString(R.string.app_name);
break;
}
if (fragment != null) {
fragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
transaction.commit();
drawerLayout.closeDrawers();
setTitle(title);
} else {
Log.w(TAG, "Error creating fragment");
}
}
Thanks!!
Based on this answer, the solution was to use
getChildFragmentManager()
instead ofgetSupportFragmentManager()
inside fragments that contains other fragments, like ViewPagers Tabs.