android中如何使用一个fragment 绑定多个viewmodel
时间: 2024-05-28 10:09:05 浏览: 29
可以使用ViewModelProviders.of()方法来创建多个ViewModel对象,每个ViewModel对象对应一个不同的Fragment。例如:
1. 在Fragment的onCreate()方法中,使用ViewModelProviders.of()方法创建ViewModel对象:
private MyViewModel1 mViewModel1;
private MyViewModel2 mViewModel2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewModel1 = ViewModelProviders.of(this).get(MyViewModel1.class);
mViewModel2 = ViewModelProviders.of(this).get(MyViewModel2.class);
}
2. 在Fragment中,通过ViewModel对象来获取数据或更新UI:
mViewModel1.getData().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String data) {
// 更新UI
}
});
mViewModel2.updateData("new data");
注意:每个Fragment都应该有自己的ViewModel对象,不要共用一个ViewModel对象。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)