当前位置:网站首页>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通信了
边栏推荐
- 吃透Chisel语言.12.Chisel项目构建、运行和测试(四)——Chisel测试之ChiselTest
- IP 实验室月复盘 · 第 5 期
- [matlab] summary of conv, filter, conv2, Filter2 and imfilter convolution functions
- Deming Lee listed on Shenzhen Stock Exchange: the market value is 3.1 billion, which is the husband and wife of Li Hu and Tian Hua
- Fs7867s is a voltage detection chip used for power supply voltage monitoring of digital system
- PHP log debugging
- 中邮科技冲刺科创板:年营收20.58亿 邮政集团是大股东
- 以房抵债能否排除强制执行
- Gorm data insertion (transfer)
- 2022 practice questions and mock exams for the main principals of hazardous chemical business units
猜你喜欢
硬件基础知识-二极管基础
C# wpf 实现截屏框实时截屏功能
小程序直播 + 电商,想做新零售电商就用它吧!
The font of markdown grammar is marked in red
[FAQ] Huawei Account Service Error Report 907135701 Common reasons Summary and Solutions
Hardware Basics - diode Basics
好博医疗冲刺科创板:年营收2.6亿 万永钢和沈智群为实控人
Use the default route as the route to the Internet
2022 Shandong Province safety officer C certificate examination question bank and online simulation examination
Understand chisel language thoroughly 12. Chisel project construction, operation and testing (IV) -- chisel test of chisel test
随机推荐
吃透Chisel语言.10.Chisel项目构建、运行和测试(二)——Chisel中生成Verilog代码&Chisel开发流程
Understand chisel language thoroughly 10. Chisel project construction, operation and testing (II) -- Verilog code generation in chisel & chisel development process
IDEA快捷键大全
QT how to detect whether the mouse is on a control
[matlab] summary of conv, filter, conv2, Filter2 and imfilter convolution functions
Doctoral application | West Lake University Learning and reasoning system laboratory recruits postdoctoral / doctoral / research internship, etc
奇妙秘境 码蹄集
R语言使用epiDisplay包的followup.plot函数可视化多个ID(病例)监测指标的纵向随访图、使用stress.col参数指定强调线的id子集的颜色(色彩)
Gorm data insertion (transfer)
ARouter的使用
Golang 使用 JSON unmarshal 数字到 interface{} 数字变成 float64 类型(转)
游戏出海,全球化运营
2022 hoisting machinery command examination simulation 100 questions simulation examination platform operation
吃透Chisel语言.07.Chisel基础(四)——Bundle和Vec
WS2818M是CPC8封装,是三通道LED驱动控制专用电路外置IC全彩双信号5V32灯可编程led灯带户外工程
MySQL 5 installation and modification free
Install and use MAC redis, connect to remote server redis
Unittest中的TestSuite和TestRunner
MySQL之详解索引
吃透Chisel语言.12.Chisel项目构建、运行和测试(四)——Chisel测试之ChiselTest