问题描述
我编写了扩展 BaSEObservable 以将其用作 MVVM 中的 viewmodel 的 Java 类,并且我需要获得一个字符串资源。通常的 getString() 不起作用,因为我没有上下文,我尝试了这个
String toFormat = Resources.getSystem().getString(R.string.playbackSpeedText);
我从中得到了 android.content.res.Resources$NotFoundException。我解决了向类构造函数添加 Context 字段的问题,但我很感兴趣,如果我可以通过另一种不使用 Context 的方式获取 String 资源。
解决方法
您可以使用 AndroidViewModel 代替 ViewModel 要么 如果您使用的是 dagger2 或 hilt,您可以创建一个注入应用程序上下文的模型,您可以在其中获取字符串
,请尝试在您的活动的通用导航器中创建 getResource(int id) 抽象方法 并在活动或基础活动中实现它,您可以在其中返回 resource.getstring(with uniqueId)
然后从您的视图模型中调用它并使用
navigator.getResource(R.string.alertmessage)
应用类中的另一种方式
Applicationclassname instance;
oncreate(){
Instance = this
}
为应用程序类的单例同步对象创建静态 getInstance() 方法并从这里返回实例对象
然后
Applicationclass.getInstance().getString(R.string.alertmessage)
在任何地方使用应用程序类实例。
,您可以通过实现此代码获得 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;
}
}