【问题标题】:Bottom Navigation Menu with Fragment activity for each [closed]每个 [关闭] 带有片段活动的底部导航菜单
【发布时间】:2017-07-21 08:00:12
【问题描述】:

项目视觉结构:Photo

问题:例如,我想知道如何将片段活动合并到底部导航抽屉“仪表板”上的按钮之一。我不想创建新的 android 活动并使用“Intent”来传递数据。我宁愿有一个片段,以便在单击“仪表板”时工具栏和底部导航抽屉不应该改变

【问题讨论】:

  • 使用布局视图组作为 Activity 中片段的容器,然后在该容器中添加或替换片段。你试过什么?
  • 能否请您稍微解释一下如何做到这一点。我完全迷失在寻找有效的方法中

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


【解决方案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 和 id fragment_container 是您的片段容器。所有的片段都会被加载到这个容器中。

然后,在您的MainActivityonCreate() 方法中,使用setContentView(R.layout.activity_main); 将此布局设置为contentView

获取我们容器元素的实例,

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

现在,当你需要改变fragment时,调用这个方法(放在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()

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多