Search code examples
androidandroid-linearlayout

How to set android layout height to x% of its parent height?


I would like to create this simple layout:

enter image description here

I wrote this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/purple_200">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.3"
        android:background="@color/black" />

</LinearLayout>

But doing so I don't see any black view appearing. What am I missing?


Solution

  • There is a new way called ConstraintLayout which is preferred. You can use layout_constraintHeight_percent property of it.

    Example

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/purple_200"
        android:orientation="vertical">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="@color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHeight_percent="0.3"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Output:

    SS