Warm tip: This article is reproduced from stackoverflow.com, please click
android android-studio

Why does the fragment_container control fill in whole screen in Android Studio?

发布于 2020-03-28 23:14:52

There are two controls, both nav_view and fragment_container.

I hope that nav_view is located on the bottom of screen , and fragment_container fill in the free space, so I write Code A.

But I find fragment_container fill in the whole screen, you can see Image A, how can I fix it?

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

Image A

enter image description here

Questioner
HelloCW
Viewed
45
Pankaj Kumar 2020-01-31 17:40

Using match_parent into fragment tag is taking the whole screen (as your navbar is not visible). For ConstarintLayout you need to use match_constraints instead match_parent to achieve what you want. Hello World is perfect in his comment.

Use below code

<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" />