android:text= "@string/hello" 和普通右键的区别 - > 文本视图组件 - > 编辑文本



当我在教程的帮助下工作时,我在textview android:text-"@string/hello"中发现了这个,它显示了一些错误。

然后我浏览了图形视图并右键单击组件并输入文本。然后该错误删除并通知我

**Hardcoded string hello should use String resources**

在 android 中,"@string/"是指包资源管理器中 Project>res>values> 位置中的字符串.xml

字符串.xml包含一个 xml 文件,该文件引用带有 id 的字符串。例如:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World</string>
    <string name="app_name">My app</string>
</resources>

这里name="hello"是id,"Hello World"是它的值。使用 @string/hello 时,将显示该值。

"@drawable/"的情况类似。它将引用使用的图像。等等。

可以通过编程方式在文本视图中设置文本。例如:

TextView tv = (TextView)findViewById(R.id.text1);     //text1 is the id u provide in xml file
tv.setText("Hello World");

我希望它对你有所帮助。

@string/hello只是注意到Android将字符串加载到位于/values目录(strings.xml)的XML文件中。

hello 是由name="hello"到该 XML 中指定的字符串的 ID。

Android Studio 非常不稳定。以前,它会在string.xml中自动生成相应的语句。因此,使用以前版本的教程会让初学者陷入困境。

string.xml的工作原理

Android Studio希望您将所有文本写在一个地方,即string.xml文件中。在所有其他文件中,您只需输入缩写。例如

android:text="@string/Hello_world"

表示在string.xml文件中查找缩写Hello_world并将其替换为所需的文本。

string.xml中,应该写的相应语句是:

<string name="Hello_world">Hello world!</string>

这应该可以完成工作!

可以只写android:text="Hello world!"(这就是硬编码)。如果你打算成为一名安卓开发者,那么你就不会最大限度地提高效率。

为什么? string.xml

将所有文本放在一个文件中可以简化许多事情。如果需要,喜欢翻译和轻松更改。但是,您应该选择有意义的缩写!

最新更新