2013-03-15 65 views
0

得到更新,当我添加此代码activity_main.xml中,我得到一个错误,因为在string.xml值不存在..String.xml不会在Android中

我应该怎么做,除了手动更改值在string.xml

<TextView 
     android:id="@+id/TextView02" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/unknown" 
     android:textSize="20dip" > 
</TextView> 
+1

你确定你要打开同一个项目的string.xml档案? – Raynold 2013-03-15 08:30:38

+0

请说明你得到了什么样的错误,以及你如何将未知变成你好世界?我认为这是你混合起来的地方。 – 2013-03-15 08:32:43

+0

我不明白你的意思是“我改变我的价值android:在main.xml中的文本” – njzk2 2013-03-15 08:41:05

回答

2

你引用一个字符串你好在的strings.xml这是不存在的strings.xml文件世界国际

您不能以编程方式更改strings.xml中的值。

您可以执行以下操作以编程方式更改textview中的文本。

TextView tv= (TextView) findViewById(R.id.TextView02); 
tv.setText("hello"); 

or 
tv.setText(getResources().getString(R.string.my_string));// refer to the string in strings.xml programatically. 

可以在XML

<TextView 
    android:id="@+id/TextView02" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="hello" 
    android:textSize="20dip" > 

设置文本的strings.xml

<string name="my_String">Hello World</string> 

在XML文件中,您可以参考上面的字符串

<TextView 
    android:id="@+id/TextView02" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/my_string" 
    android:textSize="20dip" > 

http://developer.android.com/guide/topics/resources/string-resource.html。看看链接。

以上链接为例。保存在RES /价值/ strings.xml中

XML文件:

<?xml version="1.0" encoding="utf-8"?> 
    <resources> 
    <string name="hello">Hello!</string>// hello is defined here in strings.xml 
    </resources> 

这种布局XML应用将一个字符串查看:

<TextView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello" />// resource hello is refered here. 
+0

好吧,也许我没有正确解释它。我道歉。我将我的main.xml改为我改变的代码。然后我得到了一个android:text下的红线:“@ string/unknown”,并说在string.xml中找不到值。该怎么办>摆脱红线和错误 – CanucksGirl 2013-03-15 08:51:15

+0

这是因为你必须在strings.xml中定义未知的资源。您可以在main.xml文本视图中引用相同的内容,或者以编程方式引用它以在textview中设置文本。检查你是否已经在strings.xml中定义了一个未知字符串 – Raghunandan 2013-03-15 08:54:00

+0

我刚刚更新了我的问题 – CanucksGirl 2013-03-15 09:11:08