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

后端 未结 15 2002
陌清茗
陌清茗 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:22

    Answer as of Nov 10 2016

    Splash's comment below has highlighted that it is not necessary to use a custom property type (like imageResource), we can instead create multiple methods for android:src like so:

    public class DataBindingAdapters {
    
        @BindingAdapter("android:src")
        public static void setImageUri(ImageView view, String imageUri) {
            if (imageUri == null) {
                view.setImageURI(null);
            } else {
                view.setImageURI(Uri.parse(imageUri));
            }
        }
    
        @BindingAdapter("android:src")
        public static void setImageUri(ImageView view, Uri imageUri) {
            view.setImageURI(imageUri);
        }
    
        @BindingAdapter("android:src")
        public static void setImageDrawable(ImageView view, Drawable drawable) {
            view.setImageDrawable(drawable);
        }
    
        @BindingAdapter("android:src")
        public static void setImageResource(ImageView imageView, int resource){
            imageView.setImageResource(resource);
        }
    }
    

    Old Answer

    You could always try to use an adapter:

    public class DataBindingAdapters {
    
        @BindingAdapter("imageResource")
        public static void setImageResource(ImageView imageView, int resource){
            imageView.setImageResource(resource);
        }
    }
    

    You can then use the adapter in your xml like so

    
    

    Be sure to notice that the name within the xml matches the BindingAdapter annotation (imageResource)

    The DataBindingAdapters class doesn't need to be declared anywhere in particular, the DataBinding mechanics will find it no matter (i believe)

提交回复
热议问题