me.at.coding
me.at.coding

Reputation: 17604

Force a relative size for a button?

I have two buttons in a relative layout, both have android:layout_weight="50". So as long as no button's text is greater than half the screen weight, both buttons have the same size. But when one button's text gets too long, the buttons won't have the same size anymore (please compare to the screenshot below). How can I make two buttons equally sized, therefore each of them shall have a width of half of the screen size, by giving them just a relative width like android:layout_weight="50" so that both buttons end up equally sized independent of their text length? It would be OK, if the text was cropped or something like that. Thanks for any hint!

My current XML code looks like this:

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

    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_weight="50"
        android:text="left button left button left button left button"/>

    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_weight="50"
        android:text="right button"/>

</LinearLayout>

enter image description here

Upvotes: 0

Views: 1738

Answers (2)

Shafi
Shafi

Reputation: 1368

You simply need to set the property android:layout_weight="1" in both the buttons and you will get it working the way you want.

Upvotes: 0

Mark Allison
Mark Allison

Reputation: 21909

Set android:layout_width="0dp" on both buttons.

The layout weights are only applied after the button's widths have been calculated. When you specify android:layout_width="wrap_content" the width of the text calculated before the weights are calculated, and the controls will be sized to contain the text, because you are telling the layout manager that the content of each button should wrap around its text. If you set those widths to 0dp, then the layout weights will be made equal irrespective of the size of the text within those buttons and only the weights will be taken in to account when the layout sizes & positions are calculated by the layout manager.

Upvotes: 4

Related Questions