前言
在日常的开发工作中,我们有的同学喜欢使用ButterKnife有的则热衷于DataBinding框架对于两种框架来说,各有千秋。今天的内容主要是根据我的自身实践经验,分享给大家!
依赖
启用DataBinding插件:
dataBinding {
enabled = true
}
butterknife依赖:
project.build文件
classpath ‘com.jakewharton:butterknife-gradle-plugin:10.2.1’
app.build文件
api ‘com.android.support:support-annotations:28.0.0’
implementation ‘com.jakewharton:butterknife:10.2.1’
annotationProcessor ‘com.jakewharton:butterknife-compiler:10.2.1’
IViewBinder .java
public interface IViewBinder {
/**
* 默认方法,用来初始化布局绑定方式
* @param layoutId
* @param context
* @param target
*/
default void init(@LayoutRes int layoutId, Context context, ViewGroup target) {
Object object = null;
if (layoutId == 0) {
throw new IllegalArgumentException("请选择布局文件");
}
boolean useDataBinding = userDataBinding();
try{
if (useDataBinding) {
object = DataBindingUtil.inflate(LayoutInflater.from(context), layoutId, target, true);
} else {
View view = LayoutInflater.from(context).inflate(layoutId, target, true);
object = KnifeKit.bind(this, view);
}
}catch (Exception e){
e.printStackTrace();
}