The BindingAdapter does not have to be static. It is easier to work with it if it is static. If you must use the instance method, you can, but you must provide a way for the instance to be reached through the DataBindingComponent.
Imagine you have an instance of the BindingAdapter:
public class ImageBindingAdapters {
private ImageLoader imageLoader;
public ImageBindingAdapters(ImageLoader imageLoader) {
this.imageLoader = imageLoader;
}
@BindingAdapter("url")
public void setImageUrl(ImageView imageView, String url) {
imageLoader.loadInto(imageView, url);
}
}
First, any class containing an instance of the BindingAdapter must be provided as a DataBindingComponent method. This is the created interface that you implement, and the method is based on the class name:
public class MyComponent implements DataBindingComponent {
@Override
public ImageBindingAdapters getImageBindingAdapters() {
return imageBindingAdapter;
}
}
Now you need to provide the component during the binding. For instance:
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
MyBinding binding = DataBindingUtil.setContentView(this,
R.layout.my, new MyComponent());
binding.setData();
}
Thus, it is mainly used if you use dependency injection. You can also use DataBindingUtil.setDefaultComponent()it if you do not need to change the component for each binding.
source
share