I just learn how to use data binding on Android. And I want to ask why BindingAdapter must be set to static method? If I can make it non-static method. What I must to do? I need to load my image into my own ImageLoader object.
A static binding adapter method with the BindingAdapter annotation allows you to customize how a setter for an attribute is called. The attributes of the Android framework classes already have BindingAdapter annotations created.
BindingAdapterUtils is not static and requires an object to use, retrieved from the DataBindingComponent. If you don't use an inflation method taking a DataBindingComponent, use DataBindingUtil. setDefaultComponent or make all BindingAdapter methods static.
To create a custom binding adapter, you need to create an extension function of the view that will use the adapter. Then, you add the @BindingAdapter annotation. You have to indicate the name of the view attribute that will execute this adapter as a parameter in the annotation.
The BindingAdapter doesn't have to be static. It is just much easier to work with if it is static. If you must use an instance method, you can, but you must provide a way for the instance to be reached through the DataBindingComponent.
Let's imagine that you have an instance 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, whatever class contains the instance BindingAdapter must be provided as a method of the DataBindingComponent. It is a generated interface that you implement and the method is based on the name of the class:
public class MyComponent implements DataBindingComponent {
@Override
public ImageBindingAdapters getImageBindingAdapters() {
//... whatever you do to create or retrieve the instance
return imageBindingAdapter;
}
}
Now, you have to provide the component during binding. For example:
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
MyBinding binding = DataBindingUtil.setContentView(this,
R.layout.my, new MyComponent());
binding.setData(/* whatever */);
}
So, it is mostly used if you use dependency injection. You can also use DataBindingUtil.setDefaultComponent()
if you don't need to change the component for each binding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With