首页 > 解决方案 > 为什么 fragment_container 控件在 Android Studio 中会填满整个屏幕?

问题描述

有两个控件,两者nav_viewfragment_container

我希望它nav_view位于屏幕底部,并fragment_container填充空闲空间,所以我写了代码A。

但是我发现fragment_container填满了整个屏幕,你可以看到Image A,我该如何修复它?

代码 A

<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <LinearLayout
            android:id="@+id/nav_view"
            android:layout_width="match_parent"
            android:layout_height="40dp"

            android:orientation="horizontal"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent">

    </LinearLayout>


    <fragment
            android:id="@+id/fragment_container"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"

            app:layout_constraintBottom_toTopOf="@id/nav_view"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"

            app:navGraph="@navigation/nav_graph" />


</androidx.constraintlayout.widget.ConstraintLayout>

图像 A

在此处输入图像描述

标签: androidandroid-studio

解决方案


使用match_parentintofragment标签正在占用整个屏幕(因为您的导航栏不可见)。因为ConstarintLayout您需要使用match_constraintsmatch_parent 来实现您想要的。Hello World 在他的评论中是完美的。

使用下面的代码

<fragment
            android:id="@+id/fragment_container"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:defaultNavHost="true"

            app:layout_constraintBottom_toTopOf="@id/nav_view"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"

            app:navGraph="@navigation/nav_graph" />

推荐阅读