Home » Android » android – Make buttons have the same width in layout

android – Make buttons have the same width in layout

Posted by: admin June 15, 2020 Leave a comment

Questions:

I put 4 buttons in a relative layout.
I want them to have the same width, and fix for any screen size of a phone.
My code as below:

<RelativeLayout
            android:id="@+id/relativeLayout1"
            android:layout_width="match_parent"
            android:layout_height="38dp" >

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:text="Button" />

            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/button1"
                android:text="Button" />

            <Button
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/button2"
                android:text="Button" />

            <Button
                android:id="@+id/button4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/button3"
                android:text="Button" />

        </RelativeLayout>

What should I modify?

How to&Answers:

Switch to a LinearLayout and give all the buttons equal weight.

for example:

<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="38dp"
  android:orientation="horizontal">
  <Button android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_width="match_parent" />
  <Button android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_width="match_parent" />
  <Button android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_width="match_parent" />
</LinearLayout>