底部导航菜单,每个都有Fragment活动

时间:2017-07-21 08:00:12

标签: android android-fragments android-activity navigation-drawer bottomnavigationview

项目视觉结构:Photo

问题我想知道如何将片段活动合并到底部导航抽屉上的一个按钮" Dashboard"例如。我不想创建新的Android活动并使用" Intent"传递数据。我宁愿想要一个片段,以便工具栏和底部导航抽屉不应该被点击到"仪表板"

1 个答案:

答案 0 :(得分:1)

假设您的活动布局如下:

<强> 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>

此处,标识为FrameLayout的{​​{1}}是您的片段容器。所有碎片都将被加载到这个容器中。

然后,在fragment_container的{​​{1}}方法中,使用MainActivity将此布局设置为contentView

获取容器元素的实例

onCreate()

现在,当您需要更改片段时,请调用此方法(放在setContentView(R.layout.activity_main);中):

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