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:

Version2 (DataBinding):


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.