VIEW MODEL 介绍
- 使用VIEW MODEL 保存的数据只会在系统重启,或内存吃紧被杀掉时数据才会丢失。
创建VEW MODEL实体对象
package com.example.wechatredpacket.view_model;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class UserViewModel extends ViewModel {
public static final String TAG = "UserViewModel";
private String token;
private MutableLiveData<Integer> count;
private MutableLiveData<String> userName;
private MutableLiveData<String> pwd;
public MutableLiveData<String> getUserName() {
if (userName == null) {
userName = new MutableLiveData<>();
userName.setValue("");
}
return userName;
}
public MutableLiveData<String> getPwd() {
if (pwd == null) {
pwd = new MutableLiveData<>();
pwd.setValue("");
}
return pwd;
}
public void setUserName(MutableLiveData<String> userName) {
this.userName = userName;
}
public void setPwd(MutableLiveData<String> pwd) {
this.pwd = pwd;
}
public void setToken(String token) {
this.token = token;
}
public String getToken() {
return token;
}
public MutableLiveData<Integer> getCount() {
if (count == null) {
count = new MutableLiveData<>();
count.setValue(10);
}
return count;
}
public void setCount(MutableLiveData<Integer> count) {
this.count = count;
}
}
在Fragment中实例化VIEW MODEL
userViewModel = new ViewModelProvider(getActivity(), new ViewModelProvider.NewInstanceFactory()).get(UserViewModel.class);
FragmentLoginBinding binding;
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false);\
binding.setUserViewModel(userViewModel);
binding.setLifecycleOwner(getActivity());
XML
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="UserViewModel"
type="com.example.wechatredpacket.view_model.UserViewModel" />
</data>
<EditText
android:text="@{String.valueOf(UserViewModel.userName)}"
/>
</layout>