问题
how can I switch Fragments in the new design support navigation drawer? I found example codes on the Cheesesquare Github on how to switch fragments using the TabLayout, but not the navigation drawer. Is that the same? I also would not like to recreate fragments when switching, but rather do it like the TabLayout where it retains the fragments instance and the fragment`s content is how the user left it.
回答1:
Write some code like this:
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.your_menu_id:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, getFragment(), "SET_A_TAG").addToBackStack("SET_A_TAG").commit();
break;
}
return true;
}
});
private YourFragment getFragment() {
YourFragment f = getSupportFragmentManager().findFragmentByTag("SET_A_TAG");
if (f == null) {
f = new YourFragment();
}
return f;
}
回答2:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true">
<include layout="@layout/include_list_viewpager"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@id/fragmentContainer"/>
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header"
app:menu="@menu/drawer_view"/>
Something like this?
来源:https://stackoverflow.com/questions/30816892/android-switch-fragments-in-the-new-design-support-navigation-drawer