安卓布局——layout_gravity和gravity的用法

原文链接:http://www.cnblogs.com/xiaoran1129/archive/2013/03/26/2982733.html


相信对于Android的初学者来说,大家都曾经被layout里这两个极其相似的属性迷惑过。

简单使用一下搜索工具,我们就不难找到下面这样的答案:

layout_gravity 表示组件自身在父组件中的位置 
gravity             表示组件的子组件在组件中的位置

看似很简单嘛~)

貌似大伙瞅一眼就明白了。今天我要说的就是这貌似瞅一眼就明白的道理。 
为什么这么简单的道理,总有同学会发现,在“某些时候”,layout_gravity这个属性不好使了,失去了它应有的作用。

于是同学们又开始使用搜索工具,一边还不停的骂:Google做的这个layout真他妈的不好使! 
下面我们就网上找来的一个例子来简单描述一种layout_gravity失效的情况。

<?xml version="1.0" encoding="utf-8"?>
<!-- android:gravity设置了按钮上面的文字的显示位置,而android:layout_gravity设置了按钮在布局中的显示位置。 –>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <Button android:layout_width="250dip"
                android:gravity="right"
                android:layout_height="wrap_content"
                android:text="我居右显示"
                android:layout_gravity="right" />;
</LinearLayout>

这段代码的展现效果如下:!

 

 

然后我们再看下面这段代码:

<?xml version="1.0" encoding="utf-8"?>
<!-- android:gravity设置了按钮上面的文字的显示位置,而android:layout_gravity设置了按钮在布局中的显示位置。 –>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <Button android:layout_width="250dip"
                android:gravity="right"
                android:layout_height="wrap_content"
                android:text="我居右显示"
                android:layout_gravity="right" />
</LinearLayout>


这段代码我们一样设置了android:layout_gravity="right",但是它的展现效果却是下面这样的:

 

 

于是我们前面所说的情况就发生了,“Google做的这个layout真他妈的不好使!”

问题究竟出在哪里了呢? 
细心一点的同学就会发现,下面的这段代码,最外层的LinearLayout少了这样一个属性:android
rientation="vertical" 
不错,正是缺少了这个属性才导致了android:layout_gravity="right"的失效。 
因为LinearLayout默认的是:androidrientation="horizontal"

也就是说,只有在作为父layout的LinearLayout是androidrientation="vertical"的时候,android:layout_gravity="right"才会生效。

到这里本次“讲座”可以结束了吗? No!

看完上面的内容,有同学也许还会发现,当外层的LinearLayout为androidrientation="vertical" 的时候,android:layout_gravity="bottom"失效了

看到这里相信大家都明白了

下面我们还需要做一个简单的总结: 
当作为父layout的LinearLayout的属性为android
rientation="vertical" 的时候,android:layout_gravity="?"这里设为横向的时候才能生效。比如:left,right,center_horizontal等

当作为父layout的LinearLayout的属性为androidrientation="horizental" 的时候,android:layout_gravity="?"这里设为纵向的时候才能生效。比如:top,bottom,center_vertical等;

有一个比较特殊的是center,不管是横向还是纵向的时候,它总有一个方向起作用。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值