はじめに
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つあります。これを守らないとおこられます。
-
@JvmStatic
を記載すること - objectでclassをつくること
-
@BindingAdapter(app:imageUrl)
ではなく@BindingAdapter(imageUrl)