繁体   English   中英

如何在没有上下文的 Android 中获取字符串资源?

[英]How to get a String Resourse in Android having no Context?

我编写了扩展 BaseObservable 的 java 类,以将其用作 MVVM 中的 ViewModel,我需要获得一个字符串资源。 通常的 getString() 不起作用,因为我没有 Context 并且我尝试了这个

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;
    }


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM