开发者

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开发者_JAVA技巧 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>

Force a relative size for a button?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜