欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现button居中的方法

程序员文章站 2023-11-29 22:34:46
本文实例讲述了android实现button居中的方法。分享给大家供大家参考。具体如下: 通过在main.xml 或者其他xml 布局文件中布局button的时候,选择a...

本文实例讲述了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":这个是垂直居中对齐
android:gravity="bottom":放在容器的底部
android:gravity="center" :放在容器的中心

希望本文所述对大家的android程序设计有所帮助。