当前位置:网站首页>First experience of ViewModel
First experience of ViewModel
2022-07-04 14:31:00 【Novice Xiaowang】
ViewModel The aim is to Life cycle Store and manage user interface related data in a conscious way , It can be used to manage Activity and Fragment Data in . It can also be handled Fragment And Fragment And so on .
Basic use
1. Import dependence
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
2. Create a solid object
public class User implements Serializable {
String name;
int age;
public User(String name,int age){
this.name = name;
this.age = age;
}
}
3. establish userModel Data model
public class UserModel extends ViewModel {
public MutableLiveData<User> mLiveData = new MutableLiveData<>();
public UserModel(){
// Initial value
mLiveData.postValue(new User("wang",20));
}
// update operation
public void doSomething(){
User user = mLiveData.getValue();
user.name = " Reset data ";
mLiveData.setValue(user);
}
}
4.activity quote
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 Ingenious use
1: Activity And Fragment" signal communication "
With ViewModel,Activity And Fragment Can share one ViewModel, because Fragment Is attached to Activity Upper , In instantiation ViewModel When the Activity Pass in ViewModelProviders, It will give you a Activity Created ViewModel, This Fragment You can easily access the ViewModel Data in . stay Activity Revision in China userModel After the data , The Fragment You can get the updated data .
public class MyFragment extends Fragment {
public void onStart() {
// I got it here ViewModel example , In fact, yes. Activity Created in is an instance
UserModel userModel = ViewModelProviders.of(getActivity()).get(UserModel.class);
}
}
2: Fragment And Fragment" signal communication "
Let's take an example (Google The official example )
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.
});
}
}
So let's define a ViewModel, Put some data in it , And then in MasterFragment and DetailFragment You can get this ViewModel, Got the ViewModel You can get the data in it , Equivalent to indirectly through ViewModel The communication
边栏推荐
- Popular framework: the use of glide
- 2022 game going to sea practical release strategy
- 数据湖(十三):Spark与Iceberg整合DDL操作
- MySQL stored procedure exercise
- MATLAB中tiledlayout函数使用
- 【信息检索】分类和聚类的实验
- Nowcoder reverse linked list
- scratch古堡历险记 电子学会图形化编程scratch等级考试三级真题和答案解析2022年6月
- docker-compose公网部署redis哨兵模式
- AI and Life Sciences
猜你喜欢
Talk about 10 tips to ensure thread safety
flink sql-client.sh 使用教程
使用CLion编译OGLPG-9th-Edition源码
vscode 常用插件汇总
scratch古堡历险记 电子学会图形化编程scratch等级考试三级真题和答案解析2022年6月
leetcode:6109. 知道秘密的人数【dp的定义】
【信息检索】分类和聚类的实验
[information retrieval] link analysis
潘多拉 IOT 开发板学习(RT-Thread)—— 实验3 按键实验(学习笔记)
How to package QT and share exe
随机推荐
STM32F1与STM32CubeIDE编程实例-MAX7219驱动8位7段数码管(基于GPIO)
Explain of SQL optimization
2022游戏出海实用发行策略
Supprimer les lettres dupliquées [avidité + pile monotone (maintenir la séquence monotone avec un tableau + Len)]
[cloud native] how can I compete with this database?
PyTorch的自动求导机制详细解析,PyTorch的核心魔法
Test evaluation of software testing
Leetcode T48: rotating images
Chapter 17 process memory
海外游戏代投需要注意的
A collection of classic papers on convolutional neural networks (deep learning classification)
No servers available for service: xxxx
Digi XBee 3 RF: 4个协议,3种封装,10个大功能
实战解惑 | OpenCV中如何提取不规则ROI区域
docker-compose公网部署redis哨兵模式
Chapter 16 string localization and message Dictionary (2)
An overview of 2D human posture estimation
leetcode:6110. The number of incremental paths in the grid graph [DFS + cache]
一文概览2D人体姿态估计
ML之shap:基于boston波士顿房价回归预测数据集利用shap值对XGBoost模型实现可解释性案例