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

android 相对布局

2011-03-05 11:27 288 查看
1、 相对布局的基本概念
一个控件的位置它决定于它和其他控件的关系,好处:比较灵活;缺点:掌握比较复杂。
2、 相对布局常用属性介绍
这里将这些属性分成4个组,便于理解和记忆。
a)、以下4个属性设置控件与之间的关系和位置





但是上面4个属性并没有设置各个控件之间是否对齐。
示例1:将控件A放置在控件B的上面,则使用android:layout_above属性,控件布局的效果可以有以下这么两种情况。
1、 控件A与控件B对齐,并且控件A是在控件B的上面。
2、 控件A没有与控件B对齐,但是控件A又确实是在控件B的上面。





b)、以下5个属性,设置的是控件与控件之间对齐的方式(是顶部、底部还是左、右对齐)。



示例2:在示例1的基础上,设置控件A放置在控件B的上面,使用android:layout_above属性,并且控件A的左边边缘与控件B的左边边缘对齐,使用android:layout_alignLeft属性。



c)、以下4个属性设置控件与父控件之间对齐的方式(是顶部、底部还是左、右对齐)。



d)、以下4个属性设置控件的方向。



可以通过组合这些属性来实现各种各样的布局。
注:以上属性和其他更多属性的作用都能在android的帮助文档中找到;

示例3:假如要实现一个如下图这样布局的程序



如果这样的布局要使用LinearLayout的话会比较麻烦和复杂,
1、 首先需要一个垂直布局方向的LinearLayout,包裹所有的控件;
2、 然后在第一个LinearLayout中嵌套一个垂直方向的LinearLayout,放在上部分,在这个LinearLayout中放入一个TextView和EditText;
3、 最后还是在第一个LinearLayout中嵌套一个水平方向的LinearLayout,放在第一个LinearLayout的下部分,在这个LinearLayout中放入两个Button,并且还得让它们居右。
可参考下图:



如果使用RelativeLayout会要简单很多,下面为main.xml的代码。
Java代码

1. <?xml version="1.0" encoding="utf-8"?>
2.
3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
4. android:layout_width="fill_parent"
5. android:layout_height="wrap_content"
6. android:padding="10px"
7. >
8. <TextView
9. android:id="@+id/lable"
10. android:text="Type here:"
11. android:layout_width="fill_parent"
12. android:layout_height="wrap_content"
13. />
14.
15. <EditText
16. android:id="@+id/entry"
17. android:layout_width="fill_parent"
18. android:layout_height="wrap_content"
19. android:background="@android:drawable/editbox_background"
20. android:layout_below="@id/lable"
21. />
22.
23. <Button
24. android:id="@+id/ok"
25. android:layout_width="wrap_content"
26. android:layout_height="wrap_content"
27. android:text="OK"
28. android:layout_below="@id/entry"
29. android:layout_marginLeft="10px"
30. android:layout_alignParentRight="true"
31. />
32.
33. <Button
34. android:id="@+id/cancel"
35. android:layout_width="wrap_content"
36. android:layout_height="wrap_content"
37. android:layout_toLeftOf="@id/ok"
38. android:layout_alignTop="@id/ok"
39. android:text="Cancel"
40. />
41. </RelativeLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: