通过R.string引用字符串

时间:2014-12-08 03:33:29

标签: java android

我有一个带文字的简单按钮
如果在 android:text 中我引用字符串,它就像它想象的那样工作。

<Button
            android:id="@+id/true_b"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/true_button" /> // OK



     <Button
                android:id="@+id/true_b"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@id/R.string.true_button" /> // doesn`t output anything

但是,如果我尝试通过R.string引用我的字符串。“字符串名称”没有任何反应 请解释我在哪里错过了......

2 个答案:

答案 0 :(得分:1)

这里有一些你做错的事情。要在XML中引用字符串,您应该使用

android:text="@string/string_name"

@string引用string.xml文件,string_name是您声明的名称。

这就是string.xml中所需的行看起来像

<string name="string_name">This is a string you are referencing!r</string>

此外,我从未尝试使用命名资源。分开的话。这可能会导致错误,但我不是百分百肯定。

编辑: 当michal.z说你不能引用R.或android.R时,它是非常正确的。来自XML的资源。您只在尝试以编程方式引用资源时才使用这些。

答案 1 :(得分:0)

在XML格式中,您使用@+id/@id/来指定View应具有的ID或引用先前在XML中声明的View。您不能在XML代码中引用R类,因为事实上R类是基于XML中定义的资源创建的。所以在XML中无法访问它。