Violet Giraffe
Violet Giraffe

Reputation: 33605

LinearLayout: is it guaranteed that the only match_parent item will occupy all the free space?

It had always been a bit of trouble getting one element in the layout to occupy all the remaining available space. Last I remember, match_parent and layout_weight attributes were required. But today I did this, and it works, i. e. the first item is wrapped and the second spans across all the remaining space:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </android.support.design.widget.AppBarLayout>

        <TextView
            android:id="@+id/view"
            android:background="#FF80FF00"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
</LinearLayout>

The question is whether it's guaranteed (by design), or if it's a mere coincidence that it worked the way I want it to in this particular case (i. e. cannot be relied upon).

Upvotes: 0

Views: 32

Answers (1)

Eric Liu
Eric Liu

Reputation: 1536

The guaranteed way to let one View to occupy the remaining space in the LinearLayout is by setting the layout_weight value to 1 while leaving other child views' weight attribute empty.

In the following xml example, the second child View will occupy all the remaining space between the top View and the bottom View.

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


    <View
        android:layout_width="match_parent"
        android:layout_height="50dp"
        />

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />

    <View
        android:layout_width="match_parent"
        android:layout_height="50dp"
        />

</LinearLayout>

Upvotes: 1

Related Questions