众所周知Google在几年前就有了mvvm。但是国内用的项目好像不多,kotlin大家都追捧,但是mvvm没看到几个项目在用。
android的mvvm直接在app/build.gradle下加入以下代码即可:
buildFeatures { viewBinding true dataBinding true}
加入后即可使用,但是没看到有几个封装的好的框架。所以打算自己手撸一个框架。
首先是Activity,以下是它的代码片段:
public abstract class BaseActivity<K extends ViewDataBinding,V extends BaseActivityModel> extends AppCompatActivity {
protected K binding;//只要你写了activity_main.xml,就会自己生成ActivityMainBinding
protected V model;//这里需要自己生成一个viewModel
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(null);
Log.i(this.getClass().getSimpleName(), "..........onCreate..........");
binding = bindingInflate();
setContentView(binding.getRoot());
model = bindingModel();
binding.setLifecycleOwner(this);
binding.setVariable(getVariableId(),model);
initData();
}
protected abstract int getVariableId();
protected abstract V bindingModel();
protected abstract int getTitleBarViewId();
protected abstract void initData();
protected abstract K bindingInflate();
public K getBinding() {
return binding;
}
......
以下是activity_main.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<import type="com.yudun.futuresport.binding.ViewPager2BindingAdapter"/>
<variable
name="main"
type="com.....viewmodel.activity.MainUIActivityModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
......
以下是BaseActivityModel
public class BaseActivityModel<T extends BaseActivity> {
protected T activity;
public BaseActivityModel(T activity) {
this.activity = activity;
}
}
......
现在来看看MainActivity里面有多简洁:
public class MainActivity extends BaseActivity<ActivityMainBinding, MainUIActivityModel> {
@Override
protected int getVariableId() {
return BR.main;
}
@Override
protected MainUIActivityModel bindingModel() {
return new MainUIActivityModel(this);
}
@Override
protected int getTitleBarViewId() {
return 0;
}
@Override
protected void initData() {
model.initFragment(this);
model.initDictionary();
}
@Override
protected ActivityMainBinding bindingInflate() {
return ActivityMainBinding.inflate(getLayoutInflater());
}
......
页面交互代码则写在MainUIActivityModel里面。
更多代码请等待后续更新。
网友评论