【问题标题】:Android switch Fragments in the new design support navigation drawer新设计中的Android switch Fragments 支持导航抽屉
【发布时间】:2015-06-13 09:04:06
【问题描述】:

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

【问题讨论】:

    标签: android android-fragments navigation-drawer androiddesignsupport


    【解决方案1】:

    像这样写一些代码:

    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;
    }
    

    【讨论】:

    • 但这会在我每次单击该项目时创建一个新片段。我不想要那个。我希望它保持不变,所以当我切换到另一个片段并返回时它仍然具有相同的视图,我在 EditTexts 中输入的所有文本都相同
    • 我刚注意到,这个方法去掉了工具栏?
    • @qwertz 不,它只是替换了片段。
    • 现在我注意到当我切换回片段时所有动画都会重新启动,所以似乎每次都重新加载
    • @qwertz 你在片段中做了什么吗?
    【解决方案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"/>
    

    这样的?

    【讨论】:

    • 我想你没看懂我的问题,这个问题已经有答案了
    • 哦,对不起,我以为你是另一个人。是的,除了你必须把 listpager 和 framelayout 放在一个视图中,就像一个线性布局
    • 好的,谢谢。因为我不知道如何在还有 Tablayout 的地方显示另一个片段。问题是,当我将新片段放入片段容器中时,没有显示工具栏..因为它被新片段隐藏了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多