【问题标题】:How to get a String Resourse in Android having no Context?如何在没有上下文的 Android 中获取字符串资源?
【发布时间】:2021-07-29 14:31:17
【问题描述】:
我编写了扩展 BaseObservable 的 java 类,将其用作 MVVM 中的 ViewModel,我需要获取一个字符串资源。通常的 getString() 不起作用,因为我没有上下文,我尝试了这个
String toFormat = Resources.getSystem().getString(R.string.playbackSpeedText);
我从中得到了 android.content.res.Resources$NotFoundException。我解决了向类构造函数添加 Context 字段的问题,但我很感兴趣是否可以通过不使用 Context 的另一种方式获取 String 资源。
【问题讨论】:
标签:
android
resources
android-context
【解决方案1】:
您可以使用 AndroidViewModel 代替 ViewModel
或者
如果您使用的是 dagger2 或 hilt,您可以创建一个模型来注入应用程序上下文,您可以在其中获取字符串
【解决方案2】:
请尝试在您的活动的通用导航器中创建 getResource(int id) 抽象方法
并在你可以返回resource.getstring(with uniqueId)的activity或baseactivity中实现它
然后从您的视图模型中调用它并使用
navigator.getResource(R.string.alertmessage)
应用程序类中的另一种方式
Applicationclassname instance;
oncreate(){
Instance = this
}
为应用程序类的单例同步对象创建静态getInstance()方法并从这里返回实例对象
然后
Applicationclass.getInstance().getString(R.string.alertmessage)
使用应用程序类实例在任何地方。
【解决方案3】:
您可以通过实现此代码获得string resource
public class SomeViewModel extends AndroidViewModel {
private final String toFormat;
public SomeViewModel(@NonNull Application application) {
super(application);
toFormat = application.getApplicationContext().getString(R.string.playbackSpeedText);
}
public final String getToFormat() {
return this.toFormat;
}
}