LoginSignup
8
7

More than 5 years have passed since last update.

Android DataBindingとPicasso

Last updated at Posted at 2019-02-07

はじめに

DataBindingを利用しているAndroidアプリで、
PicassoやGlideでImageViewに画像を表示させる機会に出会いませんか?
今回はBindingAdapterを用いてPicassoで画像をロードする方法を紹介します。

  • Kotlin 1.3.20
  • Picasso 2.71828

XMLのサンプル

こちらのImageViewにPicassoで画像をロードし表示させます。

item.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="viewModel"
            type="hoge.SelectCompanyItemViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/companyImageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:imageUrl="@{viewModel.imageUrl}" />

    </LinearLayout>

</layout>

Custom Bindingのサンプル

公式のドキュメントで紹介されているようにBindingAdapterを用いてメソッドを定義することにより、
XMLで定義したapp:imageUrlを紐づけることができます。
今回はKotlinっぽくImageViewに拡張関数でloadImage()を作成しました。

Util.kt
import android.databinding.BindingAdapter
import android.widget.ImageView
import com.squareup.picasso.Picasso

object Util {
    @JvmStatic
    @BindingAdapter("imageUrl")
    fun ImageView.loadImage(url: String?) {
        Picasso.get().load(url).into(this)
    }
}

注意点が3つあります。これを守らないとおこられます。
1. @JvmStaticを記載すること
2. objectでclassをつくること
3. @BindingAdapter(app:imageUrl) ではなく@BindingAdapter(imageUrl)

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7