Accessing strings.xml from ViewModel

心已入冬 提交于 2019-12-22 10:41:32

问题


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

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.

Are there any other ways?


回答1:


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

From docs:

Application context aware ViewModel.

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

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


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.

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


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

And here's what changes I've done:


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



来源:https://stackoverflow.com/questions/46443524/accessing-strings-xml-from-viewmodel

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