Anarantt
Anarantt

Reputation: 289

Refering to string through R.string

I have a simple button with text
If in android:text i refer to string it works as it suppose to.

<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

However, if i try to refer to my string through R.string."name of string" nothing happens
Explain me please where i am missing smth...

Upvotes: 0

Views: 92

Answers (2)

michal.z
michal.z

Reputation: 2075

In XML you use @+id/ or @id/ to specify the id which your View should have or to reference View previously declared in XML. You cannot reference R class in XML code because in fact R class is created on base of your resources defined in XML. So it is unreachable in XML.

Upvotes: 0

Dacotah
Dacotah

Reputation: 591

There are a few things that you are doing wrong here. To reference a string in XML you should use

android:text="@string/string_name"

@string referring to the string.xml file and string_name being the name that you have declared.

This is what the line required in string.xml would look like

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

Also I have never tried naming a resource with . separating words. This could cause an error but I am not 100% sure.

Edit: michal.z is incredibly correct when he says that you cannot reference R. or android.R. resources from XML. you only use these when you are trying to reference a resource programatically.

Upvotes: 1

Related Questions