Load Image url on ImageView by using data binding with Picasso in Kotlin

While building the android app by using the MVVM architecture design pattern with Kotlin, I faced many of issue for example data binding and ViewModel communication etc. I am sharing one of the issues which I faced to load image URL on image view with help of Picasso. I thought It would be worth to share with everyone to understand this issue and the solution.

First of all, using the data binding concept we need to add dependency inside the build.gradle file and enable the data binding feature.

For the data binding concept, I used the ObservableFields Object. ObservableFields are self-contained observable objects that have a single field. The primitive versions avoid boxing and unboxing during access operations.

Now I have to bind these two fields with the help of data binding in XML. Let see.

Here You need to focus on two things  <data> tag and  android:src=”@{vm.imageUrl}” tag. ImageUrl is the  ObservableFields of TimelineItemViewModel class.

The magic happens when we create a custom Picasso target that takes the ObservableField and handles updating its value. Let’s create the BindableFieldTarget to load the bitmap.

Now we almost were done. One thing that we need to set this imageUrl to this target in our adapter class or whatever you are using.

Great, We did so for. In my next tutorial, we will focus on MVVM architecture design pattern to used to build an awesome android application. If you are wondering the MVP design pattern with Java and Rx, then please check this post would be helpful or MVP with RxJava with Kotlin. Here is the Github link for the source code of the above sample.

Please do subscribe email to get all newsletters of this blog and if you feel that this post will help you to better understand then do not forget to subscribe, share and comment below. Ok, then I will see you in my next tutorial till then enjoy your life and happy coding 🙂

Sunil Gupta

I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.