问题
I have a String resource:
strings.xml
<resources>
<string name="myString">stringName</string>
</resources>
How do I get the String from a non-activity-class?
I can't do getResources().getString(R.string.myString)
回答1:
You have to use reference to a Context to access resources. I'd recommend extending the Application class and creating an Application Singleton, then calling:
MyApplication.getInstance().getString(R.string.myString);
Or injecting it into your class of choice.
Problem with this approach is that it would make your class harder to test, since now it uses the Android context. I'd recommend passing a string as a dependency into the non-activity class of choice via the constructor or preferred method.
public MyClass(String string){
}
来源:https://stackoverflow.com/questions/39082397/android-get-string-resource-for-a-non-activity-class