---
title: "Android中的字符串"
author: "lovecontry"
date: "2011-11-21T00:32:00Z"
tags: []
slug: "android"
draft: false
lastmod: "2011-12-07T08:57:01Z"
id: 1294601
url: "https://lovecontry.iteye.com/blog/1294601"
---

**使用字符串（string）资源**  
在一个Android工程中，我们可能会使用到大量的字符串作为提示信息。这些字符串都可以作为字符串资源声明在配置文件中，从而实现程序的可配置性。

在代码中我们使用Context.getString()方法，通过传递资源ID参数来得到该字符串，也可以在其他资源文件中引用字符串资源，引用格式为："@string/字符串资源名称。

**字符串资源XML文件的定义**

我们通过表来说明字符串资源是如何定义的，包括资源的位置、XML文件的格式、获得资源的方法和引用资源的方法等。

表字符串资源得定义和使用

资源位置

res/values/strings.xml

字符串XML文件

格式

使用&lt;?xml version="1.0" encoding="utf-8"?&gt;

&lt;resources&gt;根元素

&lt;string&gt;子元素：&lt;string name=

color\_name&gt;string\_value&lt;/string&gt;

获得字符串资源

的方法

Resources.getString()

引用字符串资源

的格式

Java代码中：R.string.string\_nameXML文件中：@\[package:]string/string\_name

下面将通过一个实例来演示资源文件的用法。在该实例中用到两个字符串资源：一个在布局文件中引用；另一个在Java代码中引用。实例步骤说明如下。

在该工程的res\\values\\目录下，创建一个字符串资源文件stirngs.xml，内容如下所示：

**Java代码：**  
&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;resources&gt;  
&lt;string name="app\_name"&gt;Test Resources&lt;/string&gt;  
&lt;string name="test\_str1"&gt;从代码中引用！&lt;/string&gt;  
&lt;string name="test\_str2"&gt;从资源文件引用！&lt;/string&gt;

&lt;/resources&gt;

在该工程的res\\layout\\目录下，定义一个布局文件test\_string.xml。在该布局文件中添加两个TextView视图对象：第一个TextView的文本内容直接引用strings.xml文件中的资源；第二个TextView的文本内容在代码中设置。

**Java代码：**  
&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;LinearLayout xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)" android:orientation="vertical"  
android:layout\_width="fill\_parent"  
android:layout\_height="fill\_parent"&gt;  
&lt;TextView  
android:text="@string/test\_str1"  
android:id="@+id/myTextView01"  
android:layout\_width="wrap\_content"  
android:layout\_height="wrap\_content" /&gt;  
&lt;TextView  
android:text=""  
android:id="@+id/myTextView02"  
android:layout\_width="wrap\_content"  
android:layout\_height="wrap\_content" /&gt;  
&lt;/LinearLayout&gt;

在工程的com.amaker.ch03.string包中，创建一个TestStringActivity类。在该类的onCreate()方法中，设置当前的视图布局，并获得TextView实例。通过Context.getString()方法，从字符串资源中获得字符串常量，并将其设置为TextView的文本内容。

**Java代码：**  
package eoe.demo.string;

import android.app.Activity;  
import android.os.Bundle;  
import android.widget.TextView;  
import com.amaker.test.R;  
/*  
\*  
\*  
\* @author 郭宏志  
\* 测试字符串资源  
\*/  
public class TestStringActivity extends Activity {  
private TextView myTextView;  
@Override  
public void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
setContentView(R.layout.test\_string);  
myTextView = (TextView)findViewById(R.id.myTextView02);  
String str = getString(R.string.test\_str2).toString();  
myTextView.setText(str);  
}

}