【问题标题】:Auto Align 3 buttons in a layout android自动对齐布局android中的3个按钮
【发布时间】:2013-07-02 18:14:47
【问题描述】:

我有一个相对布局,它是 4 个按钮。现在我正在为宽度做fill_parent。 对于第一个和第四个按钮,我可以将父级左/右对齐。但是如何正确对齐按钮 2,3 以便所有按钮之间有适当的间距。

我尝试以编程方式进行操作,但我无法移动或设置按钮的确切位置,因为有很多基于像素宽度和 dpi 的逻辑。

有什么简单的方法吗?

【问题讨论】:

  • 不能使用线性布局吗?要么就是这样,要么在运行时设置它们的大小,这很麻烦。

标签: android


【解决方案1】:

最简单的方法是将它们放在LinearLayout 中,然后分别给出layout_width="0dp"layout_weight="1"

【讨论】:

    【解决方案2】:

    简单的方法是使用带有四个按钮的LinearLayout 作为子级,其中所有子级都有一个相同的layout_weight

    不要忘记将所有按钮的android:layout_width 设置为“0dp”。

    像这样:

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="4">
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="1" />
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="2" />
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="3" />
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="4" />
    
    </LinearLayout>
    

    【讨论】:

    • 应该是 4。忘记从复制粘贴中更正。谢谢指出!
    • weightSum 在这里不是必需的。父视图默认其 weightSum 为其中的权重总和。另一方面,它并没有造成任何真正的伤害。您只需要记住在调整子视图数量及其权重时进行调整即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2014-12-08
    • 2014-09-23
    • 2023-03-05
    • 1970-01-01
    • 2016-07-16
    相关资源
    最近更新 更多