android linearlayout 的gravity属性

gravity属性的意思可以说众所周知我就不介绍了。分享下我遇到的问题。先看代码吧。

问题是:gravity在父布局中控制子布局的位置和在子布局中layout_gravity控制子布局在父布局中的位置。

效果想让textview居屏幕中心。

<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"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</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"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</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:orientation="horizontal"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/hello_world" />

</LinearLayout>

效果却是:这里写图片描述

通过现象可以发现,子布局如果调整在父布局(针对线性布局)中的位置如果线性布局是水平的那么子布局layout_gravity=center效果只能垂直居中,如果是垂直的话,子布局是水平居中的。造成这种情况的原因是什么我不知道,如果有知道的不妨留个言。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值