gravity与layout_gravity的区别

含义

gravity是相对于元素本身而言的,用于控制布局中控件的对齐方式,如果没有子控件,则表示内容的对齐方式。gravity常用值有top、bottom、left、right、center等,可以使用"|"将多个值连接起来。

layout_gravity是相对于父布局容器而言的,用于设置在父容器中的对齐方式。

例子

在LinearLayout中放置一个TextView,通过配置gravity和layout_gravity观察TextView出现的位置。
xml文件代码:在TextView中添加属性,android:layout_gravity="center"
<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=".MainActivity">
    <TextView
        android:id="@+id/view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_bright"
        android:layout_gravity="center"//设置TextView在父控件LinearLayout中居中
        android:text="@string/hello_world" />

</LinearLayout>
在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"
    tools:context=".MainActivity"
    android:gravity="center">//设置子控件TextView居中
    <TextView
        android:id="@+id/view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_bright"
        android:layout_gravity="center"
        android:text="@string/hello_world" />

</LinearLayout>

=

从上面的运行结果就可以看出,android:layout_gravity="center"是让TextView显示在Layout的中间。
android:gravity="center"则让LinearLayout中的子控件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"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/view1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_bright"
        android:gravity="center_horizontal"//添加代码的位置
        android:layout_gravity="center
        android:text="@string/hello_world" />

</LinearLayout>

TextView中没有子控件,那么它会对TextView中的内容起作用。字体在TextView中居中显示。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值