当前位置:网站首页>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
边栏推荐
猜你喜欢
No servers available for service: xxxx
数据中台概念
Sqlserver functions, creation and use of stored procedures
Count the running time of PHP program and set the maximum running time of PHP
实战解惑 | OpenCV中如何提取不规则ROI区域
92.(cesium篇)cesium楼栋分层
一文概览2D人体姿态估计
RK1126平台OSD的实现支持颜色半透明度多通道支持中文
leetcode:6109. Number of people who know the secret [definition of DP]
SqlServer函数,存储过程的创建和使用
随机推荐
Use of arouter
【云原生】我怎么会和这个数据库杠上了?
The game goes to sea and operates globally
R language ggplot2 visualization: gganimate package creates animated graph (GIF) and uses anim_ The save function saves the GIF visual animation
R language dplyr package summary_ If function calculates the mean and median of all numerical data columns in dataframe data, and summarizes all numerical variables based on conditions
[MySQL from introduction to proficiency] [advanced chapter] (IV) MySQL permission management and control
Detailed index of MySQL
WT588F02B-8S(C006_03)单芯片语音ic方案为智能门铃设计降本增效赋能
MySQL triggers
Leetcode T47: 全排列II
如何游戏出海代运营、游戏出海代投
Redis daily notes
Explain of SQL optimization
sql优化之查询优化器
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
gin集成支付宝支付
scratch古堡历险记 电子学会图形化编程scratch等级考试三级真题和答案解析2022年6月
数据埋点的一些问题和想法
2022游戏出海实用发行策略
Supprimer les lettres dupliquées [avidité + pile monotone (maintenir la séquence monotone avec un tableau + Len)]