Android. Get string resource for a non-activity class [duplicate]

。_饼干妹妹 提交于 2020-12-25 04:50:09

问题


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

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