当前位置:网站首页>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
边栏推荐
- Xcode 异常图片导致ipa包增大问题
- PyTorch的自动求导机制详细解析,PyTorch的核心魔法
- scratch古堡历险记 电子学会图形化编程scratch等级考试三级真题和答案解析2022年6月
- vscode 常用插件汇总
- 【MySQL从入门到精通】【高级篇】(五)MySQL的SQL语句执行流程
- 如何游戏出海代运营、游戏出海代投
- Industrial Internet has greater development potential and more industry scenarios
- 数据湖(十三):Spark与Iceberg整合DDL操作
- Leetcode t47: full arrangement II
- Test process arrangement (2)
猜你喜欢
开发中常见问题总结
leetcode:6109. Number of people who know the secret [definition of DP]
codeforce:C. Sum of Substrings【边界处理 + 贡献思维 + 灵光一现】
(1)性能调优的标准和做好调优的正确姿势-有性能问题,上HeapDump性能社区!
失败率高达80%,企业数字化转型路上有哪些挑战?
Rich text editing: wangeditor tutorial
统计php程序运行时间及设置PHP最长运行时间
Remove duplicate letters [greedy + monotonic stack (maintain monotonic sequence with array +len)]
Digi restarts XBee Pro S2C production. Some differences need to be noted
Data warehouse interview question preparation
随机推荐
AI与生命科学
[MySQL from introduction to proficiency] [advanced chapter] (V) SQL statement execution process of MySQL
Leetcode T48: rotating images
实战解惑 | OpenCV中如何提取不规则ROI区域
gin集成支付宝支付
流行框架:Glide的使用
One architecture to complete all tasks - transformer architecture is unifying the AI Jianghu on its own
Leetcode T48:旋转图像
LVGL 8.2 Line
WT588F02B-8S(C006_03)单芯片语音ic方案为智能门铃设计降本增效赋能
Ultrasonic distance meter based on 51 single chip microcomputer
2022游戏出海实用发行策略
【信息检索】分类和聚类的实验
富文本编辑:wangEditor使用教程
为什么图片传输要使用base64编码
LVGL 8.2 text shadow
统计php程序运行时间及设置PHP最长运行时间
LVGL 8.2 Sorting a List using up and down buttons
Detailed analysis of pytorch's automatic derivation mechanism, pytorch's core magic
sql优化之explain