介紹
- ViewModel :
將UI中的數(shù)據(jù)模塊提出來單獨管理,使得控制器Activirty Fragment變得更加簡單,只需要專注界面,不需要管理界面復(fù)雜數(shù)據(jù), 且屏幕旋轉(zhuǎn)后數(shù)據(jù)不會丟失 - LiveData :
為ViewModel 中的數(shù)據(jù)設(shè)置監(jiān)聽,數(shù)據(jù)改變時 自動刷新界面不需要以往的setText()
ViewModel 使用
加入依賴
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
創(chuàng)建ViewModel類繼承ViewModel
import androidx.lifecycle.ViewModel;
public class MyViewModle extends ViewModel {
public int index = 0;
}
里面管理數(shù)據(jù)index
如果要使用Context,可以繼承AndroidViewModel
Java中使用
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
//省略 findViewById ......
MyViewModle myViewModle = new ViewModelProvider(this).get(MyViewModle.class);
// 屏幕翻轉(zhuǎn)后 進(jìn)入時先設(shè)置數(shù)據(jù) 省略onSaveInstanceState方法
tv.setText(String.valueOf(myViewModle.index));
// 點擊數(shù)據(jù)+1
but.setOnClickListener(v -> {
myViewModle.index++;
tv.setText(String.valueOf(myViewModle.index));
});
}
LiveData 使用
ViewModle中數(shù)據(jù)使用LiveData包裝
public class MyViewModle extends ViewModel {
// public int index = 0;
private MutableLiveData<Integer> liveDataIndex;
//獲取liveDataIndex類型
public MutableLiveData<Integer> getLiveDataIndex() {
if (null == liveDataIndex) {
liveDataIndex = new MutableLiveData<>();
liveDataIndex.setValue(0);
}
return liveDataIndex;
}
//liveDataIndex 數(shù)據(jù)加1
public void addLiveDataIndex() {
getLiveDataIndex().setValue(liveDataIndex.getValue() + 1);
}
}
Java中
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
//省略 findViewById ......
MyViewModle myViewModle = new ViewModelProvider(this).get(MyViewModle.class);
// 屏幕翻轉(zhuǎn)后 進(jìn)入時先設(shè)置數(shù)據(jù) 省略onSaveInstanceState方法
tv.setText(String.valueOf(myViewModle.getLiveDataIndex().getValue()));
// 獲取LiveData包裝的數(shù)據(jù)并設(shè)置監(jiān)聽, onChanged()方法會監(jiān)聽數(shù)據(jù)改變并更新界面
myViewModle.getLiveDataIndex().observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer integer) {
tv.setText(String.valueOf(integer));
}
});
// 調(diào)用viewModle 中的方法更改數(shù)據(jù)后, 此時會調(diào)用上面的onChanged()方法
but.setOnClickListener(v -> {
myViewModle.addLiveDataIndex(1);
});
}