Why should the BindingAdapter be a static method?

I just learn how to use data binding on Android. And I want to ask why should the BindingAdapter be set to a static method? If I can make it a non-stationary method. What should I do? I need to upload an image to my own ImageLoader object.

+4
source share
1 answer

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() {
        //... whatever you do to create or retrieve the instance
        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(/* whatever */);
}

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.

+9
source

Source: https://habr.com/ru/post/1668205/


All Articles