Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select which Binding Conversion or Binding Adapter to use?

This concerns two features in the Data Binding guide (https://developer.android.com/topic/libraries/data-binding/index.html) : BindingAdapters and BindingConverions. The following examples are from the guide:


@BindingAdapter("android:paddingLeft")
public static void setPaddingLeft(View view, int oldPadding, int newPadding) {
   if (oldPadding != newPadding) {
       view.setPadding(newPadding,
                       view.getPaddingTop(),
                       view.getPaddingRight(),
                       view.getPaddingBottom());
   }
}

@BindingConversion
public static ColorDrawable convertColorToDrawable(int color) {
    return new ColorDrawable(color);
}

My questions are:

If I have two different BindingAdapters with the same method signature, how can I indicate which one to use for a given view? (without using custom field name variants such as myPaddingLeftOne, myPaddingLeftTwo, etc)

Similarly, if I have two BindingConversions which have the same input and return types, how can I indicate which to use in a given situation?

like image 920
Dave Avatar asked Dec 08 '25 05:12

Dave


1 Answers

The short answer is, you can't. If you have two Binding adapters with the same target types and same value types, the last one compiled will be the one that is used. This way you can override the implementations in the library.

Use different application namespace attributes to distinguish the two or use a method to make a conversion in your expression if that will help.

The same is true for BindingConversions.

Use a custom attribute and a BindingAdapter or an conversion function in your expression if you need to convert sometimes and not others. Binding conversions are powerful, but you should limit when you use them as they are activated any time the conversion can make an expression work. The one example used in the data binding library is converting an integer color to a ColorDrawable for use when Drawable is the parameter.

like image 131
George Mount Avatar answered Dec 10 '25 22:12

George Mount



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!