I am already having a binding adapter to load the image in the ImageView coming from the URL. Now, I need to load background image URL as the background of the Image View and I am using data binding, glide to load images and writing it in Kotlin.
How can I write a binding adapter for the same?
Here is my XML
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/ImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerInside"
app:backgroundImageUrl="@{item.backgroundImageUrl}"
app:mainImageUrl="@{item.mainImageUrl}"/>
I used the following Binding Adapter and it's working fine.
@BindingAdapter("backgroundImageUrl")
fun loadBackgroundImage(view: ImageView, imageUrl:String?)
{
Glide.with(view.context).load(imageUrl).into(object:SimpleTarget<Drawable>()
{
override fun onResourceReady(resource: Drawable, transition: Transition<in
Drawable>?)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
view.background = resource}
}
})
}
You can try as follows
try {
ImageView i = (ImageView)findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try this XML:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image_view_background"
android:layout_width="250dp"
android:layout_height="250dp"
android:background="@color/colorPrimary"
android:alpha="0.4"
app:mainImageUrl="@{item.backgroundImageUrl}"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<ImageView
android:id="@+id/image_view_main"
android:layout_width="230dp"
android:layout_height="230dp"
app:mainImageUrl="@{item.mainImageUrl}"
android:background="@color/colorPrimaryDark"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
For checking purpose I just set the alpha for the background image.
Hope this trick will help you.