当前位置:网站首页>ViewModel 初体验
ViewModel 初体验
2022-07-04 12:51:00 【菜鸟xiaowang】
ViewModel旨在以生命周期意识的方式存储和管理用户界面相关的数据,它可以用来管理Activity和Fragment中的数据.还可以拿来处理Fragment与Fragment之间的通信等等.
基本使用
1.导入依赖
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
2.创建实体对象
public class User implements Serializable {
String name;
int age;
public User(String name,int age){
this.name = name;
this.age = age;
}
}
3.创建 userModel 数据模型
public class UserModel extends ViewModel {
public MutableLiveData<User> mLiveData = new MutableLiveData<>();
public UserModel(){
//初始值
mLiveData.postValue(new User("wang",20));
}
//更新操作
public void doSomething(){
User user = mLiveData.getValue();
user.name = "重新设置的数据";
mLiveData.setValue(user);
}
}
4.activity引用
UserModel userModel = ViewModelProviders.of(this).get(UserModel.class);
userModel.mLiveData.observe(this, new Observer<User>() {
@Override
public void onChanged(User user) {
mMain2Binding.name.setText(user.name);
}
});
public void onClick(View view) {
switch (view.getId()) {
case R.id.updateUser:
userModel.doSomething();
Log.e("tag","onclick");
break;
}
}
5. ViewModel妙用
1: Activity与Fragment"通信"
有了ViewModel,Activity与Fragment可以共享一个ViewModel,因为Fragment是依附在Activity上的,在实例化ViewModel时将该Activity传入ViewModelProviders,它会给你一个该Activity已创建好了的ViewModel,这个Fragment可以方便的访问该ViewModel中的数据.在Activity中修改userModel数据后,该Fragment就能拿到更新后的数据.
public class MyFragment extends Fragment {
public void onStart() {
//这里拿到的ViewModel实例,其实是和Activity中创建的是一个实例
UserModel userModel = ViewModelProviders.of(getActivity()).get(UserModel.class);
}
}
2: Fragment与Fragment"通信"
下面我们来看一个例子(Google官方例子)
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
public class DetailFragment extends Fragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
model.getSelected().observe(this, { item ->
// Update the UI.
});
}
}
首先定义一个ViewModel,在里面放点数据,然后在MasterFragment和DetailFragment都可以拿到该ViewModel,拿到了该ViewModel就可以拿到里面的数据了,相当于间接通过ViewModel通信了
边栏推荐
- WS2818M是CPC8封装,是三通道LED驱动控制专用电路外置IC全彩双信号5V32灯可编程led灯带户外工程
- JVM 内存布局详解,图文并茂,写得太好了!
- Code hoof collection of wonderful secret place
- [R language data science]: cross validation and looking back
- 吃透Chisel语言.05.Chisel基础(二)——组合电路与运算符
- Mask wearing detection based on yolov1
- R语言使用lattice包中的bwplot函数可视化箱图(box plot)、par.settings参数自定义主题模式
- Gorm read / write separation (rotation)
- [FAQ] Huawei Account Service Error Report 907135701 Common reasons Summary and Solutions
- 2022g3 boiler water treatment examination question simulation examination question bank and simulation examination
猜你喜欢
China Post technology rushes to the scientific innovation board: the annual revenue is 2.058 billion, and the postal group is the major shareholder
苹果5G芯片研发失败:继续依赖高通,还要担心被起诉?
MySQL5免安装修改
基于YOLOv1的口罩佩戴检测
[FAQ] summary of common causes and solutions of Huawei account service error 907135701
吃透Chisel语言.12.Chisel项目构建、运行和测试(四)——Chisel测试之ChiselTest
Use the default route as the route to the Internet
Introducing testfixture into unittest framework
Understand chisel language thoroughly 09. Chisel project construction, operation and testing (I) -- build and run chisel project with SBT
MATLAB中tiledlayout函数使用
随机推荐
【C 题集】of Ⅶ
CVPR 2022 | greatly reduce the manual annotation required for zero sample learning, and propose category semantic embedding rich in visual information (source code download)
自主工业软件的创新与发展
File creation, writing, reading, deletion (transfer) in go language
2022 hoisting machinery command examination simulation 100 questions simulation examination platform operation
Ws2818m is packaged in cpc8. It is a special circuit for three channel LED drive control. External IC full-color double signal 5v32 lamp programmable LED lamp with outdoor engineering
Secretary of Homeland Security of the United States: domestic violent extremism is one of the biggest terrorist threats facing the United States at present
[C question set] of VII
使用默认路由作为指向Internet的路由
学习项目是自己找的,成长机会是自己创造的
硬件基础知识-二极管基础
R语言使用lattice包中的bwplot函数可视化箱图(box plot)、par.settings参数自定义主题模式
国内酒店交易DDD应用与实践——代码篇
2022 practice questions and mock exams for the main principals of hazardous chemical business units
游戏出海,全球化运营
Learning projects are self-made, and growth opportunities are self created
Interview disassembly: how to check the soaring usage of CPU after the system goes online?
Understand chisel language thoroughly 07. Chisel Foundation (IV) - bundle and VEC
数据仓库面试问题准备
R语言使用epiDisplay包的followup.plot函数可视化多个ID(病例)监测指标的纵向随访图、使用stress.col参数指定强调线的id子集的颜色(色彩)