Set drawable resource ID in android:src for ImageView using data binding in Android

后端 未结 15 2029
陌清茗
陌清茗 2020-12-04 09:27

I\'m trying to set drawable resource ID to android:src of ImageView using data binding

Here is my object:

public class Recipe implem         


        
15条回答
  •  执念已碎
    2020-12-04 10:18

    Never override standard SDK attributes when you create your own @BindingAdapter!

    This is not a good approach for many reasons like: it's gonna prevent obtaining benefits of new fixes on Android SDK update on that attribute. Also it might confuse developers and surely tricky for reusability (because it's un-exptected to be overrided )

    you may use different namespace like:

    custom:src="@{recipe.imageResource}"
    

    or

    mybind:src="@{recipe.imageResource}"
    

    ------ start Update 2.Jul.2018

    Namespace is not recommended to be used, so better to rely on prefix or different name as:

    app:custom_src="@{recipe.imageResource}"
    

    or

    app:customSrc="@{recipe.imageResource}"
    

    ------ end Update 2.Jul.2018

    However, I would recommend different solution as:

    android:src="@{ContextCompat.getDrawable(context, recipe.imageResource)}"
    

    context view is always available inside binding expression @{ ... }

提交回复
热议问题