当前位置:网站首页>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通信了
边栏推荐
- Understand chisel language thoroughly 03. Write to the developer of Verilog to chisel (you can also see it without Verilog Foundation)
- MySQL之详解索引
- 国内酒店交易DDD应用与实践——代码篇
- 忠诚协议是否具有法律效力
- 【Antd踩坑】Antd Form 配合Input.Group时出现Form.Item所占据的高度不对
- 吃透Chisel语言.04.Chisel基础(一)——信号类型和常量
- R语言dplyr包summarise_if函数计算dataframe数据中所有数值数据列的均值和中位数、基于条件进行数据汇总分析(Summarize all Numeric Variables)
- 【C 题集】of Ⅶ
- IDEA快捷键大全
- 2022 practice questions and mock exams for the main principals of hazardous chemical business units
猜你喜欢

vscode 常用插件汇总

【FAQ】華為帳號服務報錯 907135701的常見原因總結和解决方法

Huahao Zhongtian sprint Technology Innovation Board: perte annuelle de 280 millions de RMB, projet de collecte de fonds de 1,5 milliard de Beida Pharmaceutical est actionnaire

基于YOLOv1的口罩佩戴检测

205. 同构字符串

C# wpf 实现截屏框实时截屏功能

MySQL 5 installation and modification free

锐成芯微冲刺科创板:年营收3.67亿拟募资13亿 大唐电信是股东

How to choose a technology stack for web applications in 2022

数据仓库面试问题准备
随机推荐
IDEA快捷键大全
Understand chisel language thoroughly 04. Chisel Foundation (I) - signal type and constant
去除重复字母[贪心+单调栈(用数组+len来维持单调序列)]
Unity shader learning (3) try to draw a circle
IP 实验室月复盘 · 第 5 期
sharding key type not supported
go语言中的文件创建,写入,读取,删除(转)
The mouse wheel of xshell/bash/zsh and other terminals is garbled (turn)
China Post technology rushes to the scientific innovation board: the annual revenue is 2.058 billion, and the postal group is the major shareholder
游戏出海,全球化运营
自主工业软件的创新与发展
Unittest框架中引入TestFixture
R语言使用epiDisplay包的dotplot函数通过点图的形式可视化不同区间数据点的频率、使用by参数指定分组参数可视化不同分组的点图分布
Use the default route as the route to the Internet
[matlab] summary of conv, filter, conv2, Filter2 and imfilter convolution functions
Ruichengxin micro sprint technology innovation board: annual revenue of 367million, proposed to raise 1.3 billion, Datang Telecom is a shareholder
LiveData
Assertion of unittest framework
MATLAB中tiledlayout函数使用
英视睿达冲刺科创板:年营收4.5亿 拟募资9.79亿