Android Jetpack

Loading Images Using Data Binding – Glide

Pinterest LinkedIn Tumblr

In this blog, I will explain about Loading Images from a URL Using Glide with the help of Data Binding. In the previous blog, I have explained, How to bind View’s using data binding in Android.

Now, I will show you, how can bind the ImageView to URL to load the image. Let’s move to the AndroidStudio. You have to follow the below step for Loading Images from Url using Data Binding

Step for implementation

  • Create a new project and enable Data Binding
  • Add glide dependency on app/build. gradle file
  • Add an ImageView in activity_main.xml
  • Create a variable in the layout file inside the <data/> which will handle the URL of the image.
  • Set the variable on ImageView in the layout file.
  • Now add Internet permission in AndroidManifest
  • Create a POJO class (Model Class)
  • Finally, Initialise this image URL in Activity
1. Create a new project and enable Data Binding

Let’s open Android Studio and create a new project. After project creation you have to open the app/build.gradle and enable data binding using the below lines of code.

 //enable data binding
    dataBinding {
        enabled = true
    }
2. Add glide dependency on app/build. gradle file

In this demo, We are using Glide library for Image loading. So let’s add a dependency in build.gradle

    // Glide dependency
    implementation 'com.github.bumptech.glide:glide:4.8.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
3. Now prepare layout for presenting ImageView.

At the time of project creations. If you have selected the Empty/Basic template then MainActivity.java and activity_main.xml file will automatically create. If not you have to create an Activity with the layout file. Now open the layout file and add ImageView. Let’s add a few more components for better looks and feel.

<?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="user"
            type="com.wave.imageloading.User" />

        <variable
            name="imageUrl"
            type="String" />
    </data>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <RelativeLayout
            android:id="@+id/rellay1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/grad"
            android:paddingTop="60dp"
            android:paddingBottom="60dp">

            <RelativeLayout
                android:id="@+id/imgUser"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp"
                android:background="@drawable/circle_border">

                <ImageView
                    android:id="@+id/ivProfileImage"
                    android:layout_width="120dp"
                    android:layout_height="120dp"
                    android:layout_margin="9dp"
                    android:adjustViewBounds="true"
                    android:background="@drawable/circle"
                    android:padding="3dp"
                    android:scaleType="centerInside"
                    app:profileImage="@{imageUrl}" />

            </RelativeLayout>

            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/imgUser"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="15sp"
                android:fontFamily="@font/montserrat_alternates"
                android:text="@{user.name, default=Name}"
                android:textColor="@color/white"
                android:textSize="32sp" />

            <TextView
                android:id="@+id/tv_address"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tv_name"
                android:layout_centerHorizontal="true"
                android:fontFamily="@font/montserrat_alternates"
                android:text="@{user.address, default=Address}"
                android:textAllCaps="true"
                android:textColor="@color/address"
                android:textSize="14sp" />

        </RelativeLayout>

    </RelativeLayout>
</layout>

For loading image from URL first create a variable, which will handle the URLs of Image, and set the URL on the ImageView

4. Now add Internet permission in AndroidManifest
 <uses-permission android:name="android.permission.INTERNET" />
5. Create a POJO class (Model Class)

Now create a model class and declare some properties such as name address and profile image with getter and setter

package com.wave.imageloading;

import android.databinding.BindingAdapter;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

/**
 * Created on : Mar 24, 2019
 * Author     : AndroidWave
 */
public class User {
    private String name;
    private String address;

    public User(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @BindingAdapter("profileImage")
    public static void loadImage(ImageView view, String imageUrl) {
        Glide.with(view.getContext())
                .load(imageUrl).apply(new RequestOptions().circleCrop())
                .into(view);
    }
}

Here we are used @BindingAdapter annotation for Image URL using Glide.

6. Finally, Initialise this image URL in MainActivity

Let’s open MainActivity and replace setContentView to DataBindingSetContentView. Initialize use and profile image variables.

package com.wave.imageloading;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.wave.imageloading.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        binding.setUser(new User("Princess Diana", "USA"));
        binding.setImageUrl("https://androidwave.com/wp-content/uploads/2019/01/profile_pic.jpg");
    }
}

After following all the above step RUN the project and how it works. If you have any queries, feel free to ask them in the comment section below. Happy Coding 🙂

Read a full article on Data Binding Android

4 Comments

  1. Igor Ganapolsky Reply

    Thank you for this illustration. You should now use kapt instead of annotationProcessor

  2. I don’t understand how loadImage function in User class is connected to main class. Don’t we need to initialize the function?

    • Ahmed Radhouane Belkilani

      Using the @BindingAdapter(“profileImage”).
      check the ImageView xml implementation you will fin a custom attribute “app:profileImage”
       
       

    • Ahmed Radhouane Belkilani

      Just to add a tip, this method is static one so in kotlin you should call it from outside the activity class or in separate file like extensions.kt.
      Building the project enable the xml to recognise the method implementation

Write A Comment