Same Size Button : Without using nested linear - (Android Essentials: XML & Java)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:weightSum="90">
<Button
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="30"
android:text="B1"/>
<Button
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="30"
android:text="B2"/>
<Button
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="30"
android:text="B3"/>
</LinearLayout>
Creating buttons with equal width in a horizontal orientation without nesting layouts is simple and efficient with this XML layout snippet. This code utilizes a LinearLayout
with a horizontal orientation to place three buttons (B1
, B2
, and B3
) side by side. By assigning equal layout_weight
values and setting the layout_width
to 0dp
(which is the correct practice when using weight in a LinearLayout), each button will occupy an equal portion of the screen's width.
The weightSum
attribute of the LinearLayout
is set to "90", and each button has a layout_weight
of "30". This means that the width of the LinearLayout
is divided into three equal parts, each part being 1/3 of the total width, and each button fills one part. The total sum of the weights is equal to the weightSum
attribute of the LinearLayout
.
How to use this code:
Copy the XML code snippet.
Paste it into your layout XML file where you want these buttons to appear.
Change the
android:text
attributes to what you want the buttons to display.If desired, adjust the
android:layout_height
for theLinearLayout
and the buttons to fit your design needs.You can also customize the appearance of the buttons further by setting background, adding margins, padding, or specifying text appearance.
Here is a corrected version of the layout to ensure that the weights are used correctly with layout_width
set to 0dp
:
Remember to use 0dp
for the layout_width
when you are using the layout_weight
attribute for horizontal LinearLayout
. This will ensure that the layout is rendered correctly and each button will take up equal space, regardless of the screen size or resolution.