当前位置:网站首页>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
边栏推荐
- 卷积神经网络经典论文集合(深度学习分类篇)
- 【MySQL从入门到精通】【高级篇】(五)MySQL的SQL语句执行流程
- Supprimer les lettres dupliquées [avidité + pile monotone (maintenir la séquence monotone avec un tableau + Len)]
- Learn kernel 3: use GDB to track the kernel call chain
- Ruiji takeout notes
- Leetcode T49: 字母异位词分组
- 数据中台概念
- Xcode 异常图片导致ipa包增大问题
- Solutions aux problèmes d'utilisation de l'au ou du povo 2 dans le riz rouge k20pro MIUI 12.5
- (1)性能调优的标准和做好调优的正确姿势-有性能问题,上HeapDump性能社区!
猜你喜欢

Oppo find N2 product form first exposure: supplement all short boards

Vscode common plug-ins summary

【信息检索】链接分析

(1)性能调优的标准和做好调优的正确姿势-有性能问题,上HeapDump性能社区!

Rich text editing: wangeditor tutorial

Chapter 17 process memory

Why should Base64 encoding be used for image transmission

【MySQL从入门到精通】【高级篇】(四)MySQL权限管理与控制

Stm32f1 and stm32subeide programming example -max7219 drives 8-bit 7-segment nixie tube (based on GPIO)
![Supprimer les lettres dupliquées [avidité + pile monotone (maintenir la séquence monotone avec un tableau + Len)]](/img/af/a1dcba6f45eb4ccc668cd04a662e9c.png)
Supprimer les lettres dupliquées [avidité + pile monotone (maintenir la séquence monotone avec un tableau + Len)]
随机推荐
Oppo find N2 product form first exposure: supplement all short boards
Scratch Castle Adventure Electronic Society graphical programming scratch grade examination level 3 true questions and answers analysis June 2022
统计php程序运行时间及设置PHP最长运行时间
Why should Base64 encoding be used for image transmission
Intelligence d'affaires bi analyse financière, analyse financière au sens étroit et analyse financière au sens large sont - ils différents?
Map of mL: Based on Boston house price regression prediction data set, an interpretable case is realized by using the map value to the LIR linear regression model
Count the running time of PHP program and set the maximum running time of PHP
【云原生】我怎么会和这个数据库杠上了?
[MySQL from introduction to proficiency] [advanced chapter] (IV) MySQL permission management and control
LVGL 8.2 LED
One architecture to complete all tasks - transformer architecture is unifying the AI Jianghu on its own
sql优化之查询优化器
Incremental ternary subsequence [greedy training]
Leetcode 61: 旋转链表
Leetcode 61: rotating linked list
R language uses bwplot function in lattice package to visualize box plot and par Settings parameter custom theme mode
Respect others' behavior
Visual Studio调试方式详解
去除重复字母[贪心+单调栈(用数组+len来维持单调序列)]
R language uses the DOTPLOT function of epidisplay package to visualize the frequency of data points in different intervals in the form of point graph, and uses the by parameter to specify the groupin