常用控件 02 布局 Layout

来源:互联网 发布:爱肯拿天峻授权淘宝店 编辑:程序博客网 时间:2024/05/16 11:11

1.写xml文件:

最外层元素必须是 View 或者 ViewGroup,如:

<?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="vertical" >    <TextView android:id="@+id/text"              android:layout_width="wrap_content"              android:layout_height="wrap_content"              android:text="Hello, I am a TextView" />    <Button android:id="@+id/button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Hello, I am a Button" /></LinearLayout>
保存为.xml格式文件,并存放在项目的 res/layout/ 下。


2.加载xml文件:

调用 setContentView() 方法。如:

public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main_layout);}

3.属性(Attributes):

Attributes 分为两种:从 root View 继承而来的属性(如 ID );布局参数( layout parameters )用于描述特定的方面;
1>ID:

1)  添加 ID资源:

android:id="@+id/my_button"
@ 表示要求xml语句解析器将后边的部分解析为 ID资源,+ 表示该资源需要创建并添加到 R.java 文件中;

使用 ID 资源时:

android:id="@android:id/empty"

2)布局参数(layout Parameters):

格式:layout_something ;

每一个 ViewGroup 类都实现了继承自 ViewGroup.LayoutParams 类的内部类, 如 FrameLayout.LayoutParams, GridLayout.LayoutParams 等;

每个 LayoutParams 至少有两属性: android:layout_height 和 android:layout_width,其值通常是:具体数值,MATCH_PARENT,WRAP_CONTENT;

3)布局位置(Layout Position):

view 是一个矩形,其位置用 left 和 top 的坐标,加上 width 和 hight 两个维度表示。单位为 pixel (像素);
可以调用 getLeft() 和 getTop() 方法来获得位置;

3常见的布局:

ViewGroup 的每一个子类都是一种layout;
层次越少,显示速度越快;

1)Linear Layout :

使所有子元素按水平或垂直方向排成一排,方向由 android:orientation 属性决定。
水平方向的每行只有一个元素,垂直方向的,其高度由最高的元素加上 padding 决定;
可以使用 margins 来定义元素之间的间隔,用 gravity (right, center, 或者 left)来确定对齐方式;
用 android:layout_weight 属性来确定该元素的重要程度,默认为0,按数值比例来划分剩下的空闲空间;

2)Relative Layout:
每一个 View 的位置都由与其他元素之间的相互关系来确定;
每一个 View 的位置默认是在左上角,所以每个元素都需要指定位置;
所有的属性都可以在 RelativeLayout.LayoutParams 中找到,如:android:layout_alignParentTop,android:layout_centerVertical,android:layout_below,android:layout_toRightOf等;
可以不按照出现的顺序来定义相互之间的关系,如可以先让A below B,然后再声明B。


当布局的内容是动态的或者无法事先确定的时候,可以用 AdapterView 的子类来在运行过程中填充layout。
Adapter 将获得的数据(从资源文件或者数据库)转换成一个 View 添加到 AdapterView 中。

常见的 AdapterView 的子类有: GridView, ListView, Spinner, StackView等

3)List View

4)   Grid View






原创粉丝点击