How can we use data binding in android to put image resource in an ImageView
?
<ImageView android:id="@+id/is_synced" android:src="@{model.pending ? @mipmap/pending: @mipmap/synced}" android:layout_width="wrap_content" android:layout_height="wrap_content" />
I want an image if pending is true and another image if pending is false. But it's showing error.How can I achieve this functionality?
src: src is an attribute used to set a source file or you can say image in your imageview to make your layout attractive.
You just have to import <import type="android. content. Context" /> in your xml data imports. Then, you can access context for your databinding simply with context .
I tried this, and it works for me (buildToolsVersion: 24.0.1):
<ImageView android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="8dp" android:scaleType="centerInside" app:imageResource="@{item.avatarResId}"/>
just use app:imageResource
to replace android:src
, android:src="@{item.avatarResId}"
doesn't works else define a custom @BindAdapter("android:src")
for it.
but use app:imageResource
doesn't need define a @BindAdapter
additionally, because the ImageView has a method called setImageResource()
, when you use app:imageResource
, it will call setImageResource()
automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With