From Android to Linear Layout, weight

Asked 2 years ago, Updated 2 years ago, 33 views

While reading the Android document, I found an interesting property called weight. So I'm going to apply that I created the layout.

  <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dip"
        weight="1" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dip"
        weight="1" />

  </LinearLayout>

I tried to align it horizontally so that the two buttons split the width in half, but when I ran it, it didn't show properly. What's wrong with the first button being printed by filling up one line?

android weight

2022-09-22 16:14

1 Answers

First of all, weight is an attribute that gives a ratio, but you have to give 0 dp to the attribute that you want to give a ratio between width and height. We want to split a line equally, so we have to give the width value 0dp. Also, you have to specify the widthSum value for the layout surrounding the items, which is optional. The weight is a ratio value, so it has values from 0.00 to 1.00. You gave me 1 and 1 for the same two buttons. If you want half and half and half, It is correct to give the weightSum value as 2.

weight is an attribute that takes up a place by the ratio based on the value of weightSum. For example,

    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="5">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="2" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

    </LinearLayout>

If you did it like this, the output result is

1

It's going to be like this.


2022-09-22 16:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.