问题
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