Search code examples
androidkotlinandroid-databindingandroid-binding-adapter

BindingAdapter in Android


I am following this course about RecyclerView and Databinding.

I've read What is the use of binding adapter in Android?.

Other than make custom/more complex setter, what is the benefit of using BindingAdapter over the "normal" way ? Is there a gain in performance ?

Version1:

  • xml:

     <TextView
        android:id="@+id/sleep_length"
        android:layout_width="0dp"
        android:layout_height="20dp"
        ...
        tools:text="Wednesday" />
    
  • Adapter:

    fun bind(item: SleepNight) {
        val res = itemView.context.resources
        sleepLength.text = convertDurationToFormatted(item.startTimeMilli, item.endTimeMilli, res)
    }
    

Version2 (DataBinding):

  • xml:

    <TextView
        android:id="@+id/sleep_length"
        android:layout_width="0dp"
        android:layout_height="20dp"
        app:sleepDurationFormatted="@{sleep}"
        ...
        tools:text="Wednesday" />
    
  • Adapter:

    fun bind(item: SleepNight) {
        binding.sleep = item
    }
    
  • BindingUtils:

    @BindingAdapter("sleepDurationFormatted")
    fun TextView.setSleepDurationFormatted(item: SleepNight){
           text = convertDurationToFormatted(item.startTimeMilli, item.endTimeMilli, context.resources)
    }
    

Solution

  • Binding Adapter gives you a pretty good feature in customization of a view. Seems weird!.

    First, Suppose you have an ImageView that shows the country flag.

    Accept: Country code(String)

    Action: Show the flag of the country, if the country code is null, make ImageView GONE.

    @BindingAdapter({"android:setFlag"})
    public static void setFlagImageView(ImageView imageView, String currencyCode) {
        Context context = imageView.getContext();
        if (currencyCode != null) {
            try {
                Drawable d = Drawable.createFromStream(context.getAssets().open("flags/"+currencyCode.toLowerCase()+".png"), null);
                imageView.setImageDrawable(d);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
        else{
                imageView.setVisibility(View.GONE);
        }
    }
    

    So now you can reuse this BindinAdapter any elsewhere.

    People who loves DataBinding, see that they can reduce amount of code and write some logic in xml. Instead of helper methods.

    Second, By databinding, you will ignore findViewById, because a generated file would be created for you.

    Regarding performance, I don't find in official documentation any indicate that BindingAdapter increases performance.