How to bind ImageView with Android DataBinding

In this android programming source code example, we are going to bind ImageView with Android DataBinding.

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

Below is a step by step source code to bind ImageView with Android DataBinding.

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.androidview2.firebaseMlKitAndDataBinding.FirebaseMlKitAndDataBindingActivity17.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.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.BindingAdapter;
import androidx.databinding.DataBindingUtil;

import android.os.Bundle;
import android.widget.ImageView;

import com.bluapp.androidview2.R;
import com.bluapp.androidview2.databinding.ActivityFirebaseMlKitAndDataBinding17Binding;

public class FirebaseMlKitAndDataBindingActivity17 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityFirebaseMlKitAndDataBinding17Binding binding = DataBindingUtil.setContentView(this, R.layout.activity_firebase_ml_kit_and_data_binding17);
        DataBindingImageView imagedata = new DataBindingImageView();
        imagedata.setProfilepic(R.drawable.profilepic);
        binding.setImageview(imagedata);
    }

    public static class DataBindingImageView {
        private int profilepic;

        public void setProfilepic(int profilepic){
            this.profilepic = profilepic;
        }

        public int getProfilepic(){
            return profilepic;
        }

        @BindingAdapter({"android:image"})
        public static void loadImage(ImageView view, int profilepic){
            view.setImageResource(profilepic);
        }
    }
}

app/build.gradle

dataBinding {
        enabled = true
    }

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