Android 布局资源
2018-02-18 14:13 更新
在Android中,屏幕的视图通常从XML文件加载。这些XML文件称为布局资源。
例子
下面显示了布局文件的示例
<?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/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>
注意
/res/layout/ 子目录中的每个文件都将基于扩展名被排除的文件的名称生成一个唯一的常量。
有了布局,重要的是文件的数量。使用字符串资源,重要的是文件中单个字符串资源的数量。
例如,如果在 /res/layout/ 下有两个文件,名为file1.xml 和 file2.xml,那么在 R.java 中有以下条目。
public static final class layout {
//.... any other files
public static final int file1=0x7f030000;
public static final int file2=0x7f030001;
//....
}参考
在这些布局文件中定义的视图,如:TextView,可以通过其在R.java中生成的资源ID在Java代码中访问:
TextView tv = (TextView)this.findViewById(R.id.text1);
tv.setText("Try this text instead");
常量 R.id.text1 对应于为TextView定义的ID。布局文件中TextView的ID如下所示:
<TextView android:id="@+id/text1" .. </TextView>
id属性的值表示使用称为text1的常量来唯一标识此视图。
@+id/text1 中的加号( + )意味着将创建ID text1(如果它不存在)。
在布局资源中使用字符串资源
将字符串定义为资源后,你可以直接在视图上设置它们。
下面显示了一个示例,其中HTML字符串设置为 TextView 的文本内容。
以下代码用于string.xml。
<resources>
<string name="simple_string">simple string</string>
<string name="tagged_string">
Hello <b><i>Slanted Android</i></b>, You are bold.
</string>
</resources>
以下代码用于 layout.xml 。
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/tagged_string"/>
TextView 自动实现这个字符串是一个HTML字符串,并相应的遵守其格式。
以上内容是否对您有帮助:

免费 AI IDE


更多建议: