Saturday, December 1, 2018

Android How to create Buttons of equal width in a row on any Screen width | How to implement linearlayout with 2 buttons, Horizontal and Vertical | Set two buttons to same width regardless of screen size

It is a common requirement to layout a bunch of buttons side by side. Making them of equal width is just plain good GUI design.
To achieve the effect above, first create a LinearLayout just for the buttons. The layout will contain three buttons.

<LinearLayout android:id="@+id/linearLayout1"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent">
    <Button
        android:id="@+id/button_accept"
        android:text="Accept"
        android:layout_weight="1"
        android:layout_height="40sp"
        android:layout_width="0dp"/>
    <Button
        android:id="@+id/button_reject"
        android:text="Reject"
        android:layout_weight="1"
        android:layout_height="40sp"
        android:layout_width="0dp"/>
    <Button
        android:id="@+id/button_ignore"
        android:text="Ignore"
        android:layout_weight="1"
        android:layout_height="40sp"
        android:layout_width="0dp"/>
</LinearLayout>
We took these steps to get the effect:

1. For the LinearLayout we set android:layout_width="fill_parent". This causes the layout view to take up the full width available from the device.

2. For each Button, we set android:layout_width="fill_parent" and android:layout_weight="1".


No comments:

Post a Comment