Android button 居中


在main.xml 或者其他xml 布局文件中布局Button的时候,选择Android:gravity="center_horizontal",意思是Place object in the horizontal center of its container, not changing its size.
我们用RelativeLayout 布局,这样可以使不同的组件有对齐的方式。
给出main.xml 代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/gallerytext"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TextView>
<Gallery android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Gallery>
<Button android:id="@+id/btngal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="20sp"
   android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="返回主界面"/>
</RelativeLayout>

图示结果如下:

Android button 居中


可以看到Button 与Gallery的对齐方式是居中对齐,也即Button 与Parent居中对齐。
另外,
android:gravity="CENTER_VERTICAL“:Place object in the vertical center of its container, not changing its size. 这个是垂直居中对齐
android:gravity="BOTTOM”:Push object to the bottom of its container, not changing its size.放在容器的底部
android:gravity="CENTER“ :Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.放在容器的中心

相关内容