Android Eclipse - 如何使按钮居中

时间:2014-08-21 01:11:38

标签: android eclipse

我无法在屏幕上显示Buttons中心。顶部的文字位于中心,但接下来的2 Buttons位于左侧和垂直中心。我如何才能使它们成为水平中心? Ť

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="6dip"
    android:layout_gravity="center_horizontal"
    android:gravity="center_vertical"
    tools:ignore="HardcodedText"  >
    <TextView
        android:id="@+id/lnTotal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Your total is 0"
        android:textSize="16sp"/>
    <Button
        android:id="@+id/btnAdd"
        android:layout_width="250sp"
        android:layout_height="wrap_content"
        android:text="Add one"
        android:textSize="12sp"
        android:layout_below="@+id/lnTotal"/>
   <Button
        android:id="@+id/btnSubtract"
        android:layout_width="250sp"
        android:layout_height="wrap_content"
        android:text="Subtract one"
        android:textSize="12sp"
        android:layout_below="@+id/btnAdd"/>        
</RelativeLayout>

1 个答案:

答案 0 :(得分:1)

这取决于您使用的布局。使用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="match_parent"
    tools:context=".Mainpage">

    <Button
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_round" />

</RelativeLayout>

正如您可能已经知道的那样,两行代码将Button置于中间android:layout_centerVertical="true"android:layout_centerHorizontal="true"