[Android] DataBindingのBindingAdapterでGlideを使う
bindした時にGlideで画像を読み込んで欲しいのでBindingAdapterを実装します。
こういうデータクラスを作ります。もちろん他のプロパティがあっても大丈夫です。
data class Image(
val uri: Uri
)
レイアウトファイルを作ります。この例はRecyclerViewのアイテム用のレイアウトファイルです。先ほど作ったImageをvariableとしてバインドします。ImageViewに対して app:imageURI="@{image.uri}"
としてUriを渡します。
<?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">
<data>
<variable
name="image"
type="com.okuzawats.sampleapp.model.Image"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/thumbnail"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
app:imageURI="@{image.uri}"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="@id/information"/>
<LinearLayout
android:id="@+id/information"
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="@id/thumbnail"
app:layout_constraintEnd_toEndOf="parent">
<!-- 略 -->
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
あとは適当なKotlinのファイルを作ってBindingAdapterを実装すればOKです。
@BindingAdapter("imageURL")
fun ImageView.imageURI(uri: URI) {
Glide.with(this)
.load(uri)
.into(this)
}
書いている人 😎

茨城県つくば市在住のモバイルアプリケーションアーキテクト(Androidが得意です)。モバイルアプリのアーキテクチャ、自動テスト、CI/CDに興味があります。いわゆる「レガシーコード」のリファクタリング・リアーキテクチャが好きです。
👉 もっと詳しく
著書 ✍
Android 依存性注入 ヒッチハイク・ガイド🧳
Androidアプリでの依存性注入(Dependency Injection)に入門するためのガイダンスです。依存性注入の概念やメリットを理解し、Dagger Hiltを用いてAndroidアプリに適用する方法を解説しています。
ソフトウェアデザイン 2023年6月号📚
特集「クリーンアーキテクチャとは何か?」の第5章「モバイルアプリ開発における実践」を執筆しました。
Android クリーンアーキテクチャ ヒッチハイク・ガイド🧳
Androidアプリでのクリーンアーキテクチャに入門するためのガイダンスです。クリーンアーキテクチャの概念を理解し、Androidアプリに適用する方法を解説しています。
Android ユニットテスト ヒッチハイク・ガイド🧳
Androidアプリのユニットテストに入門するためのガイダンスです。初学者が混乱せずにAndroidアプリのユニットテストを書き始めることができる、ということを目的としています。
Android MVVMアーキテクチャ入門🛠
Androidアプリ開発の初学者に向けた、MVVM(Model-View-ViewModel)アーキテクチャの入門書を書きました。初学者の方を確実にネクストレベルに引き上げる技術書です。NextPublishingより出版されています。
関連記事 👀
- GitHub ActionsでSonarCloudにカバレッジをアップロードする
- [Android] Uniflowを用いたMVI的なアーキテクチャを試してみる🦄
- [Android] 単体テスト用の依存関係をHiltで解決する
- 俺のパブリックリポジトリ
- GitHub ActionsでktlintとAndroid Lintを並列実行して、DangerでPRにまとめてコメントする🐝