首页 > 解决方案 > FrameLayout 是否应该是不同片段的容器

问题描述

我有一个关于 Android 中 Fragments 设计的一般性问题。我的应用程序中有一个 BottomNavigationBar,我打算使用 Jetpack 导航组件(我还没有这样做)。我想要一个活动和多个片段(因为这是每个人都告诉我使用的)。现在不同的片段应该显示在一个容器中,对吧?我可以为此使用 FrameLayout 并将所有片段放入其中吗?当然,片段不应该同时显示,而是取决于选择了哪个片段。我已经为应该用作容器的 Activity 创建了一个示例 XML 布局文件,并在其中插入了两个 Fragment。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        app:labelVisibilityMode="labeled"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorGreen"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_navigation"
        app:itemIconTint="@color/colorPrimaryDark"
        app:itemTextColor="@color/colorAccent"
        />




    <FrameLayout
        android:id="@+id/container_frame"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"
        app:layout_constraintTop_toTopOf="parent"

    <fragment
        android:id="@+id/info_fragment"
        android:name="com.example.td.barapp.Info_Fragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"
        app:layout_constraintTop_toTopOf="parent"

        ></fragment>

    <fragment
        android:id="@+id/info_fragment2"
        android:name="com.example.td.barapp.Info_Fragment2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"
        app:layout_constraintTop_toTopOf="parent"

        ></fragment>
        />

</androidx.constraintlayout.widget.ConstraintLayout>

这是正确的方法吗?或者一个 Activity 还能如何服务多个 Fragment?我必须以某种方式将它们与活动联系起来,对吗?

我会很感激每一条评论,并非常感谢您的帮助。

标签: androidandroid-fragmentscontainers

解决方案


推荐阅读