繁体   English   中英

如何在线性布局中定位按钮

[英]How to position buttons in linear layout

我在水平 LinearLayout 中有两个按钮。 他们目前彼此相邻,最左边。 我想将第二个按钮移动到 LinearLayout 的右端。 我在这些按钮上尝试了 android:gravity 但这根本没有改变它们的位置。 谢谢

最简单的方法是使用RelativeLayout 你可以在右边给你想要的Button属性alignParentRight="true"

<Button
    ...
    android:layout_alignParentRight="true"/>

对于水平LinearLayoutandroid:layout_graivty (这是你想要什么,而不是android:gravity )左右不会做任何事情,因为Views已经从右侧放置到左。

如果您不确定这些, 请参阅有关android:gravityandroid:layout_gravity之间区别的答案

编辑

根据您需要/想什么,有可能用一个做到这一点LinearLayout虽然可能仍然更容易和更加灵活的RelativeLayout 无论如何,您可以使用weight来实现类似的目标并使用这些值。 下面给我一个Button在左侧和Button在右边。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Left Button"/>
<View
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:text="Right Button"/>
<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Right Button"/>
</LinearLayout>

您无法使用LinearLayout实现此目的。
改用RelativeLayout并将每个按钮放置在相对于RelativeLayout右侧或左侧。 类似于下面的例子:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignParentRight="true"
        android:text="Button" />

</RelativeLayout>

尝试将左侧按钮的layout_gravity设置为left (或start ),将右侧按钮的layout_gravityright (或end )。

问题是您目前正在使用gravity

指定对象应如何在其自身边界内在 X 轴和 Y 轴上定位其内容。

相反,您应该使用layout_gravity

孩子提供给父母的标准重力常数。 定义子视图在其封闭布局内的 X 轴和 Y 轴上的定位方式。

换句话说 - 您当前正在告诉按钮如何对齐它们的子视图,而不是告诉它们如何在其父视图中对齐。

您可以设置android:layout_weight='1'并且两个按钮将平均共享屏幕(并排),或者如果您想要它们之间的额外空间,您可以在线性布局中放置一个按钮并设置android:layout_gravityleftright的每个。

添加一个RelativeLayout并将值设置为layout_marginLeftlayout_marginTop等。

例如。 android:layout_marginLeft="32dp" android:layout_marginTop="160dp"

使 linearLayout 方向垂直,并根据需要设置按钮的重力 =>中心

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM