Thursday, February 21, 2019

Layout weight

Sometime we need views with ratio width follow screen width.
For example, we need a LinearLayout horizon with 4 textView, each one cover ¼ screen width.
We will use Layout weight.
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="150dp"
            android:layout_gravity="center_horizontal"
            android:layout_weight="1"
            android:background="@drawable/line2"
            android:textColor="#800000"
            android:textSize="15sp" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="150dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="-1dp"
            android:layout_weight="1"
            android:background="@drawable/line2"
            android:textColor="#800000"
            android:textSize="15sp" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="150dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="-1dp"
            android:layout_weight="1"
            android:background="@drawable/line2"
            android:textColor="#800000"
            android:textSize="15sp" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="150dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginLeft="-1dp"
            android:layout_weight="1"
            android:background="@drawable/line2"
            android:textColor="#800000"
            android:textSize="15sp" />
    </LinearLayout>


We must set width= 0 for views, android:layout_width="0dp"
If want to fix LinearLayout width, change first line to
android:layout_width="280dp"
Now each textView will be smaller.


If you want second textView two times bigger than anothers, set it layout_weight to 2.



No comments:

Post a Comment