android中的Button按钮居中(水平垂直中)

今天发现一个很怪异的事


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


下图为理想效果:

 

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

 

 

<LinearLayout 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="com.example.xuhao.tongzhiapplication.MainActivity"
    android:weightSum="1">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="tongZhi"
        android:text="启动通知" />
</LinearLayout>

 

 

 

效果却是这样的:

 

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

正确的写法是:

 

<LinearLayout 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"
    android:gravity="center"
    tools:context="com.example.xuhao.tongzhiapplication.MainActivity"
    android:weightSum="1">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="tongZhi"
        android:text="启动通知" />
</LinearLayout>

 

在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的内容了

 

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

  • 22
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值