【问题标题】:How to space out items in a LinearLayout?如何在 LinearLayout 中分隔项目?
【发布时间】:2011-05-23 22:57:05
【问题描述】:

我想创建一个如下所示的工具栏:

如何在 XML 中做到这一点?这是我目前的样子:

<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/toolbarLinearLayout" android:background="@color/solid_yellow">
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/replyButton" android:text="Reply"></Button>
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RT" android:id="@+id/rtButton"></Button>
        <Button android:id="@+id/dmButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="DM"></Button>
    </LinearLayout>

【问题讨论】:

    标签: java android eclipse android-layout android-linearlayout


    【解决方案1】:

    看起来你可能想要 LinearLayout 的 padding 属性,例如

    android:padding="5dip"
    

    要使每个项目占用相同的空间,请使用 layout_weight,例如

     <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/toolbarLinearLayout" android:background="@color/solid_yellow">
        <Button android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="wrap_content" android:id="@+id/replyButton" android:text="Reply"></Button>
        <Button android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="wrap_content" android:text="RT" android:id="@+id/rtButton"></Button>
        <Button android:id="@+id/dmButton" android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="wrap_content" android:text="DM"></Button>
    </LinearLayout>
    

    只要所有元素的权重相同,它们就应该占据相同的空间。 layout_width="fill_parent" 将确保填满整个栏。

    【讨论】:

    • 这将把它填满。这很好,但我希望左右距离是等距的,并且像上图一样间隔更明显。
    • 我尝试添加 paddingLeft & paddingRight 但按钮之间的空间没有被填充
    • 嘿,我已经稍微更新了我的答案 - 希望这更符合您的要求。
    【解决方案2】:

    像这样定义你的工具栏:

    <LinearLayout ...>
        <Button android:id="@+id/replyButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ...
            />
        <View
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            />
        <Button ...
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <!-- etc. -->
    </LinearLayout>
    

    所有多余的空间都将分配给按钮之间的透明视图。

    【讨论】:

      【解决方案3】:

      为线性布局中的项目添加 android:layout_margin="some value"。这对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-27
        • 1970-01-01
        • 2017-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多