Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Image resource to ImageView using DataBinding [duplicate]

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?

like image 293
George Thomas Avatar asked Jan 05 '16 08:01

George Thomas


People also ask

Which attribute is used to set an image in ImageView?

src: src is an attribute used to set a source file or you can say image in your imageview to make your layout attractive.

How do you pass context in databinding?

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 .


1 Answers

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.

like image 97
Spark.Bao Avatar answered Sep 19 '22 18:09

Spark.Bao