为什么center_horizontally不会水平居中一个元素?(Why does center_horizontally not center an element horizontally?)

我有以下布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal" android:layout_marginRight="00px" android:text="Slot1" /> <Button android:id="@+id/load" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/start" android:text="Slot2" /> <Button android:id="@+id/stat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/load" android:text="Slot3" /> </RelativeLayout>

我希望这三个盒子在布局上水平居中。 但他们是左翼的。 这是为什么? 以及如何解决它?

I have the following layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal" android:layout_marginRight="00px" android:text="Slot1" /> <Button android:id="@+id/load" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/start" android:text="Slot2" /> <Button android:id="@+id/stat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/load" android:text="Slot3" /> </RelativeLayout>

and I expected the three boxes to be centered horizontally on the layout. But they are left-alignes. Why is that? And how to fix it?

最满意答案

使用layout_centerHorizo​​ntal =“true”

重力用于放置视图内部的元素(按钮的文本)。

Layout_gravity用于LinearLayout和FrameLayout

layout_centerHorizo​​ntal,layout_centerVertical,layout_centerInParent用于在RelativeLayout中居中。 要对齐边,您可以使用layout_alignParentLeft,layout_alignParentRight,layout_alignParentTop和layout_alignParentBottom。

Use layout_centerHorizontal="true"

Gravity is used for placement of elements internal to the view (the text of the button).

Layout_gravity is used for LinearLayout and FrameLayout

layout_centerHorizontal, layout_centerVertical, layout_centerInParent are used for centering in a RelativeLayout. To align to the sides you'd use layout_alignParentLeft, layout_alignParentRight, layout_alignParentTop and layout_alignParentBottom.

更多推荐