說完了ViewModel該說說Activity了,畢竟ViewModel創(chuàng)建好了钾军,還沒有地方使用。
一丁眼、MVVM之Activity
之前的DemoActivity只是把xml用databinding綁定了蹬刷,ViewModel的生命周期感知還沒掛載到Activity中,于是就經(jīng)過了這樣一番改造性含。
public class DemoActivity extends AppCompatActivity {
protected ActivityDemoBinding mDataBinding;
protected AClass mViewModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initAAC();
}
/**
* 初始化AAC組件
*/
private void initAAC() {
mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_demo);
mViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(AClass.class);
SparseArray<Object> variableSA = new SparseArray<>();
variableSA.put(BR.aClass, CastUtil.cast(new AClass()));
if (variableSA != null && variableSA.size() > 0) {
for (int i = 0; i < variableSA.size(); ++i) {
final int variableId = variableSA.keyAt(i);
final Object variableValue = variableSA.valueAt(i);
mDataBinding.setVariable(variableId, variableValue);
}
}
//讓ViewModel擁有View的生命周期感應(yīng)
if (mViewModel != null) {
getLifecycle().addObserver(mViewModel);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
//銷毀DataBinding
if (mDataBinding != null) {
mDataBinding.unbind();
}
}
}
通過getLifecycle().addObserver(mViewModel);來給ViewModel注冊生命周期感應(yīng)豁状。到此知态,基本的雛形就算搭建完成了巢价。