每个带有片段 activity 的底部导航菜单

Bottom Navigation Menu with Fragment activity for each

项目视觉结构:Photo

问题: 例如,我想知道如何将片段 activity 合并到底部导航抽屉 "Dashboard" 上的其中一个按钮。我不想创建新的 android activity 并使用 "Intent" 来传递数据。我宁愿想要一个片段,以便在单击 "Dashboard"

时工具栏和底部导航抽屉不应该被更改

假设以下是您的 activity 布局:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 
    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:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.design.widget.CoordinatorLayout>

在这里,ID 为 fragment_containerFrameLayout 是您的片段容器。所有的片段都会被加载到这个容器中。

然后,在您的 MainActivityonCreate() 方法中,使用 setContentView(R.layout.activity_main);

将此布局设置为 contentView

获取容器元素的实例,

FrameLayout fragmentContainer = (FrameLayout) findViewById(R.id.fragment_container);

现在,当你需要改变片段时,调用这个方法(放在MainActivity):

public void changeFragment (Fragment fragment, String fragmentName) {

    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.replace(fragmentContainer, fragment);
    fragmentTransaction.addToBackStack(fragmentName);
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    fragmentTransaction.commit();
}

如果您使用支持库中的支持片段,请使用 getSupportFragmentManager() 而不是 getFragmentManager()