0

如何在新设计支持导航抽屉中切换片段?我在 Cheesesquare Github 上找到了有关如何使用 TabLayout 切换片段的示例代码,而不是导航抽屉。那是一样的吗?我也不想在切换时重新创建片段,而是像 TabLayout 那样保留片段实例,片段的内容是用户离开它的方式。

4

2 回答 2

0

写一些这样的代码:

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;
}
于 2015-06-13T09:11:56.623 回答
0
<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"/>

像这样的东西?

于 2015-06-13T13:26:08.393 回答