Android的用户界面是由一系列的View和ViewGroup对象组成的。View对象通常是一些UI组件如Button,TextView等,而ViewGroup则是View的容器,是不可见的,并能定义View的分布方式。
Android提供了XML,使得你能将你需要的View元素层次化的定义在XML中。这种将UI布局放在XML中的方式非常重要,尤其对于程序开发中多分辨率的支持来说。对于新手来说,最好不要用Eclipse中的所见即所得的方式开发自己的布局,要习惯在XML编辑器中开发自己的布局。
1.LinearLayout
LinearLayout是ViewGroup的子类,能以横向或竖向的方式排列其中的子类。可以通过属性android:orientation对其进行设置Vertical 或 Horizontal。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
</LinearLayout>
android:layout_width 和android:layout_height用来定义组件的大小。Android 2.2(API level 8)之后,Google建议使用match_parent代替,fill_parent,因为一些显示上的原因。
2.在LinearLayout中添加一个编辑框EditText
EditText是View的子类,用来显示可编辑的文本域。
<EditText android:id="@+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
android:id给组件指定了一个独一无二的标志,使你能够在代码中引用它,建议使用系统自带的ID。
如果你想在XML中引用一个资源对象,你需要使用@符号,后边跟着资源的类型,再之后是资源的名称。不同的资源类型能够使用相同的名字命名资源。
当你想给一个组件指定ID的时候,需要使用+号,这样SDK工具在编译的时候能够在项目的gen/R.java中使用ID的值为它指定一个标志,并将标志和你的组件关联。
android:layout_width和android:layout_height中使用wrap_content, 指定组件的大小正好能够包裹组件的内容。
android:hint用来指定EditText中的提示信息,它指向了一个已经定义好的字符资源。
3.添加字符资源
android项目中的字符资源位于res/valuse/strings.xml,在strings.xml中定义字符串能使我们的项目开发更加简洁,更加易于更新字符文本。也在多语言支持上起到了重要的作用。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
</resources>
4.添加一个按钮Button
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
添加Button之后的效果图。
5.使EditText占满剩余屏幕的宽度
使用android:layout_weight来指定组件在屏幕中所占的比重。所有组件的默认比重值是0,所以当我们仅指定一个组件的比重大于0时,它会占满屏幕上剩余的空间。
为了提高布局的性能,我们把width的值改为0dp,这样避免了系统重复的对宽度值进行计算。
<EditText
android:layout_weight="1"
android:layout_width="0dp"
... />
设置layout_weight为1之后的效果图。
下面是构建完成之后的布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<EditText android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
</LinearLayout>
运行之后就可以看到效果了。