阅读了@tynn的答案后,DataBindingComponent类也可以作为数据绑定方法的“对象”范围。与以静态方式设置所有方法不同,以下示例可用于扩展和自定义。例如,我们为ImageView、TextView和View类型设置了3个绑定方法。您可以首先设置接口(就像Retrofit 2为API设置接口一样)。
1. 首先设置3个接口
ImageViewBindingInterface.java
public interface ImageViewBindingInterface {
@BindingAdapter({"bind:imageUrl", "bind:error"})
public void loadImage(ImageView view, String url, Drawable error);
}
TextViewBindingInterface.java
public interface TextViewBindingInterface {
@BindingAdapter({"bind:font"})
void setFont(TextView textView, String fontName);
}
ViewBindingInterface.java
public interface ViewBindingInterface {
@BindingAdapter("android:paddingLeft")
public void setPaddingLeft(View view, int padding);
@BindingAdapter("android:onViewAttachedToWindow")
public void setListener(View view, ViewBindingAdapter.OnViewAttachedToWindow attached);
}
2. 根据 @tynn 所提到的,DataBindingComponent.java文件应该自动更新,更新后的内容如下所示。
如果您查看Android Studio中默认的DataBindingComponent类,您会发现它位于build/generated/source/apt/dev目录中。
public interface DataBindingComponent {
example.com.testerapplication.binding.ViewBindingInterface getViewBindingInterface();
example.com.testerapplication.binding.TextViewBindingInterface getTextViewBindingInterface();
example.com.testerapplication.binding.ImageViewBindingInterface getImageViewBindingInterface();
}
3. 构建自己的绑定实现方法。
BaseImageViewBinding.java
public class BaseImageViewBinding implements ImageViewBindingInterface{
@Override
public void loadImage(ImageView view, String url, Drawable error) {
Picasso.with(view.getContext()).load(url).error(error).into(view);
}
}
BaseTextViewBinding.java
public class BaseTextViewBinding implements TextViewBindingInterface {
@Override
public void setFont(TextView textView, String fontName) {
textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName));
}
}
BaseViewBinding.java
public class BaseViewBinding implements ViewBindingInterface {
@Override
public void setPaddingLeft(View view, int padding) {
view.setPadding(padding,
view.getPaddingTop(),
view.getPaddingRight(),
view.getPaddingBottom());
}
@Override
public void setListener(View view, ViewBindingAdapter.OnViewAttachedToWindow attached) {
}
}
4. 设置自己的数据绑定组件
public class MyOwnDefaultDataBindingComponent implements android.databinding.DataBindingComponent {
@Override
public ViewBindingInterface getViewBindingInterface() {
return new BaseViewBinding();
}
@Override
public TextViewBindingInterface getTextViewBindingInterface() {
return new BaseTextViewBinding();
}
@Override
public ImageViewBindingInterface getImageViewBindingInterface() {
return new BaseImageViewBinding();
}
}
5. 在应用程序中设置默认的 DataBindingComponent
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
DataBindingUtil.setDefaultComponent(new MyOwnDefaultDataBindingComponent());
}
}
使用这种方法制作自定义数据绑定应该是没有问题的,并且可以进行扩展。