关于过去的问题 How to get a ViewModel?,以及我发现的例子,它并没有解决我的问题.我没有在那里发表评论的许可,所以我不得不再问一遍.我没有ViewModelProviders类,我想在我找到的所有示例和文
model = ViewModelProviders.of(this).get(Something.class);
在Android Studio中,我没有找到“android.arch.lifecycle:extensions”作为依赖项添加.当我搜索时,它说“无需显示”.我在API 27.
因此,尝试使用未弃用的元素,我在片段中有这个:
public class EventDetailsFragment extends Fragment { EventViewModel viewModel; @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ViewModelProvider.Factory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication()); // HERE IS THE ISSUE: Seems not good practice to have to create a new ViewModelProvider every time this Fragment is created. // Perhaps I should just create a singleton ViewModelProvider in the Activity or Application, // so here could call getActivity().getViewModelProvider(this, factory). ViewModelProvider viewModelProvider = new ViewModelProvider(this, factory); viewModel = viewModelProvider.get(EventViewModel.class); ... }
我该怎么办?
打开app / build.gradle,找到依赖项块并手动将生命周期依赖项添加到列表中:dependencies { implementation 'android.arch.lifecycle:extensions:1.1.1' // ... }
同步项目,之后您应该能够获得ViewModel的实例.