Android DEV2:视图(View)
用户界面通过View和ViewGroup对象来呈现。
widgets继承自View类,而layouts继承自ViewGroup类。
使用XML布局文件
ADT会在R类中生成与XML布局文件同名的变量,用于引用该布局文件。对于布局文件内的资源,如果指定了ID,则会在R.id类中生成相应的同名变量。
布局文件格式:
文件名main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:id="@+id/textView1" /> </LinearLayout>
这里@+id/textView1表示为TextView对象指定引用名称textView1,这样保存后将自动在R.id类中生成相应的变量。
而@string/hello则是引用变量,意思是该变量名为hello,是在string类中指定的:
文件名string.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, Main!</string> <string name="app_name">ActivityCycle</string> </resources>
这样,便可以在代码中使用布局和相应的资源了!在这之前,先对照看下R类吧(Resources的缩写,提了这么久应该瞟一眼了^^):
文件名R.java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.msra.xiaobin;
public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class id { public static final int textView1=0x7f050000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } }
下面的代码在Activity中设置使用main.xml布局文件:
setContentView(R.layout.main);
获得布局文件中定义的资源(TextView类需要引用包:import android.widget.TextView; 其实按Ctrl+Shift+O就能自动引用相应的包了):
TextView textView1 = (TextView)findViewById(R.id.textView1);
注意:findViewById方法只能获取已经装载的布局文件中的资源,因此必须在setContentView之后使用。在这里装载了的布局文件是main.xml,因此只能引用main.xml中的资源。虽然其他布局文件也在R.id类中生成相应的变量。
使用代码控制视图
有以下几种方式:
1. 用findViewById方法获取指定的视图对象。
2. 获取视图容器:
LinearLayout mainLinearLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.main, null);
setContentView(mainLinearLayout);
3. 获取视图容器并将其动态加载到其他视图容器中:
LinearLayout testLinearLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.test, mainLinearLayout);
或
LinearLayout testLinearLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.test, null);
mainLinearLayout.addView(testLinearLayout);
4. 动态创建视图对象并加载:
EditText editText = new EditText(this);
testLinearLayout.addView(editText);
注意:一个视图对象只能有一个视图容器。在布局文件中的视图对象已有自己的视图容器(即根节点),因此,不能将XML文件中的非根节点的视图添加到其他视图容器中。