• android中的Button按钮居中(水平垂直中)
  • 2025-06-13 20:48:02
  • 今天发现一个很怪异的事

    Android Studio中居然一个简单的按钮水品垂直居中都写不出来

    下图为理想效果:

    可是当我写原始出代码的时候(如下):

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="com.example.xuhao.tongzhiapplication.MainActivity"

    android:weightSum="1">

    android:id="@+id/button"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_gravity="center"

    android:onClick="tongZhi"

    android:text="启动通知" />

    效果却是这样的:

    这并不是水平和垂直都居中的,只有垂直居中了,这就相当尴尬了,学了一学期的安卓突然发现这么简单的效果都不会,于是痛定思痛,好了不跟大家废话了,直接上代码

    正确的写法是:

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:gravity="center"

    tools:context="com.example.xuhao.tongzhiapplication.MainActivity"

    android:weightSum="1">

    android:id="@+id/button"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_gravity="center"

    android:onClick="tongZhi"

    android:text="启动通知" />

    在Button的父容器LinearLayout中加上

    android:gravity="center"

    这行代码

    好了,万事大吉了

    因为上面我没有写LiearLayout的orientation属性(方向属性),如果不写默认为水平方向horizontal,这时不在LiearLayout中写

    android:gravity="center"

    就只能在垂直方向居中

    同理,orientation=vertical(指定为垂直方向布局),这时不在LiearLayout中写

    android:gravity="center"

    就只能在水平方向居中

    ------------------------------------------------以下是我的理解-----------------------------------------------------

    因为

    android:layout_gravity="center"

    是针对于控件的位置起作用的

    android:gravity="center"

    是针对内容起作用的

    Button在LinearLayout中也相当于是LinearLayout的内容了

    好吧解释的我自己都觉得有些许的牵强,等我找到更合理的解释了在更新