XML (works):
android:text="@android:string/ok"
android:text="@android:string/cancel"
Java (works):
R.string.some_string_that_I_have_added_to_strings_xml
Java (does NOT work: cannot find symbol variable cancel/ok):
R.string.cancel
R.string.ok
… even though they are used in an example at https://developer.android.com/guide/topics/ui/dialogs and show up at https://developer.android.com/reference/android/R.string .
I have also tried to import android.R.string;
with no difference.
So how come the compiler complains that they are missing and how can I fix this?
CodePudding user response:
you are probably importing (on top of the file) your.package.name.R
, there is no ok
or cancel
in it, so wrong reference when R.string.ok
. When you add import android.R.string;
then you have access to system values by string.ok
, not R.string.ok
(as you probably still importing apps R
and all R.string...
are referencing to it). try to use android.R.string.cancel
straight in code, without any additional import, for forcing Android system resources, not app own.
you also may use import android.R
instead own packages R
, but note that then you have to write your.package.name.some_string_that_I_have_added_to_strings_xml
in code for accessing own resources (as only one R
may be imported, other ones must be written with full package). Much more convenient and most common way is to import own packages R
on top of file, then use R.string
prefix for own resources and short android.R.string
"full" prefix for system resources in code
(also this expands to all other kinds of resources ofc)
CodePudding user response:
If your strings are written inside values folder in strings.xml then you can access it like this:
strings.xml
<string name="OK">OK</string>
<string name="Cancel">Cancel</string>
XML layout
android:text="@string/OK"
android:text="@string/Cancel
Code:
This depends on where are you trying to call resources from. But inside Activity/Fragment you can do this
textView.setText(getResources().getString(R.string.OK)
textView1.setText(getResources().getString(R.string.Cancel)
this will use strings from strings.xml. Shortcut for this inside Activity is
getString(R.string.OK)
There is no need for 'android.R.string'
This is for strings that are defined in your strings.xml and nothing else. Important to remember is that R.string.yourString returns INT and not STRING. That's why you need getString() to get String. Also, when you write android.R.string.cancel
it will read from android built-in string resources and not your strings.xml file.