您的位置:首页 > 移动开发 > Android开发

android layout_gravity和gravity的区别

2016-04-22 11:45 309 查看
layout_gravity 表示组件自身在父组件中的位置

gravity 表示组件的子组件在组件中的位置

android:gravity 属性是对该view中内容的限定.比如一个button 上面的text. 你可以设置该text 相对于view的靠左,靠右等位置.

android:layout_gravity是用来设置该view相对与父view 的位置.比如一个button 在linearlayout里,你想把该button放在linearlayout里靠左、靠右等位置就可以通过该属性设置.

看一下例子1:`

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




例子2:

<?xml version="1.0" encoding="utf-8"?>
<!--android:gravity设置了按钮上面的文字的显示位置,而android:layout_gravity设置了按钮在布局中的显示位置。 –>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizental"
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:orientation这个属性的值变了,所以才会显示不一样

当作为父layout的LinearLayout的属性为androidrientation=”vertical” 的时候,android:layout_gravity=”?”这里设为横向的时候才能生效。比如:left,right,center_horizontal等

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

有一个比较特殊的是center,不管是横向还是纵向的时候,它总有一个方向起作用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: