“PA03”的版本间的差异
小 (移动Android chapter 3至PA03) |
(没有差异)
|
2013年2月3日 (日) 00:06的最后版本
本章及接下来几章将深入分析Android SDK的基本原理,探讨资源、ContentProvider和Intent。这3个概念是理解Android编程的基础,为理解后继章节的内容打下坚实的基础。
字符串资源 示例strings.xml文件 <?xml version="1.0" encoding="utf-8"> <resource> <string name="hello">hello</string> <string name="app_name">hello appname</string> </resource>
无论有多少资源文件,始终只有一个R.java文件。
R.java示例
public final class R { ...other entries depending on your project and application public static final class string { ...other entries depending on your project and application public static final int hello=0x7f040000; public static final int app_name=0x7f040001; ...other entries depending on your project and application } ...other entries depending on your project and application }
使用变量名hello和app_name定义的两个static final int是资源ID,表示相应的字符串资源。通过R.string.hello可以在源代码中的任何位置使用这些资源ID。 大多数示例应用程序都在一个strings.xml文件中定义所有字符串,这只不过是一个惯例。android接受任务数量的任意文件,只要xml文件的结构与stings.xml类似,并且文件位于/res/values子目录中。
布局资源 在android中,屏幕的视图通常以资源的形式从xml文件加载。这些xml文件称为布局资源。
使用布局文件
public class HelloWorldActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView)this.findViewById(R.id.text1); tv.setText("Try this text instead"); } … }
从setContentView(R.layout.main)这一行可以看到,有一个静态类R.layout,这个类中有一个常量main(一个整数),它指向xml布局资源文件定义的一个view。这个xml文件名为main.xml,需要将它放在资源的layout子目录下。
示例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:id="@+id/text1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/b1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
@+id/text1中的加号(+)表示,如果ID text1不存在,将创建它。
需要为每个屏幕(或activity)定义一个独立的布局文件。更准确来讲,每个布局需要一个专门的文件。如果绘制两个屏幕,可能需要两个布局文件,比如/res/layout/screen1_layout.xml和/res/layout/screen2_layout.xml。
多个布局文件对应多个常量
public static final class layout { .... any other files public static final int file1=0x7f030000; public static final int file2=0x7f030001; }
资源引用语法 无论什么类型的android资源(到目前为止我们介绍了字符串和布局)都使用它们在java源代码中的id来标识(或引用)。将id分配给xml文件中资源的语法称为资源引用语法。上面的@+id/text1示例中的id特性语法具有以下正式结构: @[package:]type/name type对应于R.java中一种可用的资源类型命名空间,包括:
- R.drawable
- R.id
- R.layout
- R.string
- R.attr
- R.plural
- R.array
已编译和未编译的android资源 如果将资源文件(包括xml文件)放在/res/raw目录下,它们将不会编译为二进制格式。必须使用明确基于流式传输的api来读取这些文件。音频和视频文件属于这一类别。 资源编译器会编译除raw资源以外的所有资源,并将它们全部放到最终的.apk文件中。此文件包含android应用程序的代码和资源,相当于java中的.jar文件(apk代表android package)。
android关键资源 看一下ID生成的特征,尽管我们没有看到任何官方声明,但如果xml文件位于除res/values子目录以外的任何地方,那么ID就会基于文件名而生成。如果它们位于values子目录中,则只会根据文件的内容来生成ID。