Get a string resource from “values” folder in Android

ぃ、小莉子 提交于 2020-12-06 12:22:53

问题


I have a default string that needs to be used on the app, no matter the language.

Thinking that it should be independent from the app language I did not put the string inside any of the string.xml files for the different languages. Instead I created another myString.xml file inside values folder, looking like that:

myString.xml

<resources>
    <string name="myStringResource">This text shall be available
for the entire app no matter the language
</string>
</resources>

But now I am not able to access this string.

Is it the wrong way to do that? And if yes, then how can I achieve the above explained scenario?


回答1:


To access Strings, you do as Berat said in his answer. From code using ID's (R.string.resName) and XML using the @string annotation: @string/resName to get the String.

However, when you use code (e.g. Java), you can't just use the ID. You also have to use Context.getString(R.string.resName); to get the actual String. So if you want to access the String from code and get it as a variable, you do this:

String res = context.getString(R.string.myStringResource);

I write context because it is a class in Context. You can, however, use Activity instances to get the String as well. If you are writing the code inside an activity, you can just write String res = getString(R.string.myStringResource);.

Activity means either extending Activity or AppCompatActivity (or a class that extends either on some level)



来源:https://stackoverflow.com/questions/46214345/get-a-string-resource-from-values-folder-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!