MVVM设计模式主要是view通过中间件viewModel与model数据模型交互,咱们可以看一下流程图:
本篇采用谷歌自带DataBinding 组件实现MVVM,只需要在app.gradle开启就行:
dataBinding {
enabled = true
}
View布局文件xml:
View接口:
package com.freddy.chat;
/**
* Created by xie on 2020/10/15.
*/
public interface MainView {
void moveText(int offset);
}
View层Activity:
public class MainActivity extends AppCompatActivity implements MainView {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setViewModel(new MainViewModel(this));
}
@Override
public void moveText(int offset) {
binding.tvTest.setTranslationX(offset);
}
}
业务层viewModel中间件:
package com.freddy.chat;
import android.view.View;
/**
* Created by xie on 2020/10/14.
*/
public class MainViewModel {
private String name = "测试";
private MainModel model;
private MainView view;
// @BindingAdapter("android:text")
// public static void onTextChange(TextView view, CharSequence text) {
// Log.e("tag", String.valueOf(text));
// }
public MainViewModel(MainView view) {
this.view = view;
this.model = new MainModel();
model.setName(name);
}
public MainModel getModel() {
return model;
}
public void getData(View v) {
model.setName("MVVM测试");
view.moveText(100);
}
}
Model数据模型:
package com.freddy.chat;
package com.freddy.chat;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import com.android.databinding.library.baseAdapters.BR;
/**
* Created by xie on 2020/10/14.
*/
public class MainModel extends BaseObservable {
private String name;
@Bindable
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);//刷新指定属性UI,刷新所有属性采用notifyChange();
}
}
兼容带ButterKnife老版本版本通过抽象方法isMvvM()控制:
protected abstract boolean isMvvM();
if (!isMvvM()) {
ButterKnife.bind(this);
}
兼容有BaseActivity封装 setContentView版本:
@Override
protected void onCreate(Bundle savedInstanceState) {
...
setContentView(getContentView());
...
}
protected View getContentView() {
View root = LayoutInflater.from(this).inflate(R.layout.activity_base, null);
FrameLayout content = (FrameLayout) root.findViewById(R.id.content_frame);
View contentView = LayoutInflater.from(this).inflate(getContentResource(), null);
content.addView(contentView);
if (isMvvM()) binding = DataBindingUtil.bind(contentView);
return root;
}
public T getBinding() {
return (T) binding;
}
MVVM优势:
MVVM缺点:
你们的点赞、评论就是我更新文章的动力,希望我的文章输出能帮助到一点正在努力中的你,大家一起加油哦!
欢迎关注微信公众号!你的每个赞和在看,都是对我的支持!