Android布局权重(layout_weight)不起作用

5
我正在处理一个包含5个按钮的碎片。当它在像平板这样的更大屏幕上时,我使用一个将所有5个按钮放在顶部的碎片。我将它们的layout_width都设置为1,但是按钮并没有像预期那样均匀地分布在屏幕上。
期望结果: [ all ][ my ][buttons][ go ][ here ]
实际结果: b1 b2 b3 b4 b5 b3和b5只是一个按钮...只是显示它破坏一个单词并将其放在一行下面。 [all][my][but ][go][her] 并把它放在下面一行。 [tons] [e ]
我尝试了不同的方法,但是无法使其改变。任何帮助将不胜感激。谢谢。
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/xlarge_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<Button
    android:id="@+id/tip_btn"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/tip_button"
    android:onClick="tipButton">
</Button>

<Button
    android:id="@+id/preference"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/settings"
    android:onClick="showPreferences">
</Button>

<Button
    android:id="@+id/rate_btn"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/rate_button"
    android:onClick="rateButton">
</Button>

<Button
    android:id="@+id/feedback_btn"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/feedback_button"
    android:onClick="feedbackButton">
</Button>

<Button
    android:id="@+id/cancel_btn"
    android:layout_width="0px"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="@string/exit_button"
    android:onClick="cancelButton">
</Button>
</LinearLayout>

1
请提供您的XML布局以查看错误。 - Iñigo
抱歉,我本来打算做这个的,但是忘记了。在这里。它没有将按钮均匀地间隔开,它们都挤在一起。它们都只有一个单词,并且其中两个单词被分成了两行。 - Jason Crosby
2个回答

28
简短回答:将按钮的layout_width设置为0。layout_weight用于确定如何在布局中在元素之间分配剩余空间。 因此,如果您不将宽度设置为零,则按钮内容的大小将影响它们的大小。
以下是两篇好的博客文章,解释权重如何工作: http://blog.stylingandroid.com/archives/297 http://blog.stylingandroid.com/archives/312

1
当原始帖子的XML已将所有按钮的宽度设置为零时,为什么这是被接受的答案? - me--
1
因为在回答问题时没有提到XML。 - Marcus Forsell Stahre
在Stack Overflow上制造混乱的专业技巧:将答案中的解决方案应用到你的问题上。 - undefined

8

由于您正在使用layout_weight,因此应将layout_width设置为0dp。这样就可以正常工作。


而且layout_height应该设置为0dp。 - AnkitRox

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接