Android UI Layout总结系列之篇之5大布局
By Long Luo
在一个Android应用中,Layout是开发中的一个很重要环节,Layout是组成UI不可缺少的一部分。
Android UI核心类
在Android应用构建UI的方法有以下几种:
- 单纯使用JAVA代码
- 使用XML完全定义界面
- 结合使用两者,在XML中定义,在JAVA中引用和修改
Android SDK中关于UI的核心类:
Android.view.View和android.view.ViewGroup
android中的常见UI控件均会扩展View和ViewGroup其中有一部分是专门用来控制其子View位置和大小,这些类我们称为布局管理器。
ViewGroup
- LayoutParams是ViewGroup内部类,包含了ViewGroup的布局参数,用来告诉它们的父类它们想怎么在父类中布局(大小和位置),所有在LayoutParams及其子类中定义的布局参数在xml中定义都是通过layout_***定义的。
LayoutParams只提供了两个参数设定:
layout_width 元素的高度(fill_parent | match_parent | wrap_content | *dip)
layout_height 元素的宽度(同上)
- MarginLayoutParams也是ViewGroup一个内部类,它继承了LayoutParams类,用来扩展LayoutParams的属性,设置参数。
MarginLayoutParams添加了四个参数设定:
layout_marginLeft 相对于本元素左边界的偏移
layout_marginRight 相对于本元素右边界的偏移
layout_marginTop, 相对于本元素上边界的偏移
layout_marginBottom 相对于本元素下边界的偏移
以上的两种Layout参数,所有布局中的子ViewGroup和子View都可以使用
5种Layout
下面讲讲5种布局:
1. Linear Layout (线性布局)
线性布局是Android布局中最简单的布局,也是最常用,最实用的布局。 android:orientation线形布局的对齐方式 : vertical(垂直) 和 horizontal(水平) LayoutParams中的特殊参数:
layout_weight 权值
layout_gravity 相对于父元素的重力值(默认top|left):
(top|bottom|left|right|center_vertical|fill_vertical |center_ horizontal
|fill_ horizontal | center| fill)
LinearLayout有两个非常相似的属性:
android:gravity
android:layout_gravity
他们的区别在于:
- android:gravity属性是对该view中内容的限定.比如一个button 上面的text. 你可以设置该text相对于view的靠左,靠右等位置.
- android:layout_gravity是用来设置该view相对与父view的位置.比如一个button在linearlayout里,你想把该button放在linearlayout里靠左、靠右等位置就可以通过该属性设置.
android:gravity用于设置View中内容相对于View组件的对齐方式,而android:layout_gravity用于设置View组件相对于Container的对齐方式。
原理跟android:paddingLeft、android:layout_marginLeft有点类似。如果在按钮上同时设置这两个属性。
android:paddingLeft="30px" 按钮上设置的内容离按钮左边边界30个像素
android:layout_marginLeft="30px" 整个按钮离左边设置的内容30个像素
下面回到正题, 我们可以通过设置android:gravity=“center”来让EditText中的文字在EditText组件中居中显示;
同时我们设置EditText的android:layout_gravity=“right”来让EditText组件在LinearLayout中居右显示。看下效果:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:text="one"
android:layout_gravity="right"/>
</LinearLayout>