How to use data binding with ImageView in Android Kotlin

In this android kotlin source code example, we are going to use data binding with ImageView in Android Kotlin.

You can copy and adopt this source code example to your Kotlin android project without reinventing the wheel.

Below is a step by step source code to use data binding with ImageView in Android Kotlin.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable
            name="imageview"
            type="com.bluapp.kotlinview.imageView.ImageViewActivity13.DataBindingImageView"/>
    </data>
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="30dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:image="@{imageview.profilepic}"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>


</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import androidx.databinding.DataBindingUtil
import com.bluapp.kotlinview.R
import com.bluapp.kotlinview.databinding.ActivityImageView13Binding

class ImageViewActivity13 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding:ActivityImageView13Binding = DataBindingUtil.setContentView(this, R.layout.activity_image_view13)
        val imagedata = DataBindingImageView()
        imagedata.profilepic = R.drawable.profilepic
        binding.imageview = imagedata
    }

    class DataBindingImageView {
        var profilepic: Int = 0

        companion object{
        @JvmStatic
        @BindingAdapter("android:image")
            fun loadImage(view: ImageView, profilepic: Int) {
                view.setImageResource(profilepic)
            }
        }

    }


}

build.gradle

apply plugin: 'kotlin-kapt'
kapt "com.android.databinding:compiler:3.5.0"

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment