从ViewModel访问strings.xml [英] Accessing strings.xml from ViewModel

查看:185
本文介绍了从ViewModel访问strings.xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Dagger 2 DataBindng和具有ViewModels的新Android Lifecycle组件.

I am using Dagger 2 DataBindng and the new Android Lifecycle components, which have ViewModels.

在我的ViewModel内部,我如何访问我的strings.xml?起初我在想将Context注入到viewModel中,但是,这只会泄漏内存.

Inside my ViewModel how could I get access to my strings.xml? I was thinking at first, to inject a Context into the viewModel, however, this will just leak memory.

还有其他方法吗?

推荐答案

有一个

There is an AndroidViewModel, which receives Application instance as parameter.

来自文档:

可识别应用程序上下文的 ViewModel .

子类必须具有一个接受 Application 作为唯一参数的构造函数.

Subclasses must have a constructor which accepts Application as the only parameter.

您可以使用该参数从strings.xml中检索字符串.

You can retrieve a string from strings.xml using that parameter.

链接中的存储库使用 ViewModel ,而不使用AndroidViewModel.如果我将ViewModel扩展为使用 AndroidViewModel 并包含 Application -它尝试插入 MyApplication 而不是 Application 很有道理.

The repo in the link, however uses ViewModel and not AndroidViewModel. If I extend my ViewModel to use AndroidViewModel and include the Application - it's trying to inject MyApplication instead of Application if that makes sense.

我已经检出了 GithubBrowserSample .这是UserViewModel的样子:

I've checked out GithubBrowserSample. Here's how UserViewModel looks like:



    public class UserViewModel extends ViewModel {
        ...
        @Inject
        public UserViewModel(UserRepository userRepository, RepoRepository repoRepository) {
            ...
        }
        ...
    }

这是我所做的更改:



    public class UserViewModel extends AndroidViewModel {
        ...
        @Inject
        public UserViewModel(Application application, UserRepository userRepository, RepoRepository repoRepository) {
            super(application);
            ...
        }
        ...
    }

这篇关于从ViewModel访问strings.xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆