AndroidでDataBinding
を使ってFirebase Storage
から画像を読み込む方法です。
Glide
も一緒に使います。Kotlinで書いています。
セットアップ
FirebaseとDataBindingのセットアップは割愛します。
Glide
KotlinでGlideを使う場合は、
dependencies {
implementation 'com.github.bumptech.glide:glide:4.11.0'
kapt 'com.github.bumptech.glide:compiler:4.11.0'
}
→本家のgithubでは2つ目はannotationProcessor
でしたが、Kotlinではkapt
を使います。
次に、AppGlideModule
を継承したクラスを作成します。
@GlideModule
class MyAppGlideModule : AppGlideModule() {
}
これで、自動的にGlideApp
が使えるようになります。
Firebase Storage UI
通常のFirebaseに加え、Firebase UIも追加します。
dependencies {
implementation 'com.firebaseui:firebase-ui-storage:7.1.1'
}
GlideでFirebase Storageの読み込み
Glideそのままでは、Firebase Storageの読み込みに対応していないので、StorageReferenceを読み込めるようにします。
@GlideModule
class MyAppGlideModule : AppGlideModule() {
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.append(
StorageReference::class.java, InputStream::class.java,
FirebaseImageLoader.Factory()
)
}
}
GlideでImageViewに画像を読み込み
データモデルは
data class Image(val path: String)
path
はFirebase Storageのパスとします。
DataBindingを使い、GlideからImageViewで読み込むためには、
object ImageBindingAdapter {
@JvmStatic
@BindingAdapter("imageURL")
fun ImageView.imageURI(string: String?) {
if (string == null || string.isEmpty()) { return }
val reference = FirebaseStorage.getInstance().getReference(string)
GlideApp.with(this.context)
.load(reference)
.into(this)
}
}
object
で定義し、@JvmStatic
と@BindingAdapter("imageURL")
アノーテーションを付けます。
次に、xmlレイアウトファイルで以下のように記述します
<?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.example.Image" />
</data>
.....
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
imageURL="@{image.path}"
/>
.....
</layout>
これで、Firebase Storageから画像をImageViewに読み込みができます。
※画像へのアクセス権がある前提です。
参考
https://torajirousan.hatenadiary.jp/entry/2020/05/19/101907
https://github.com/bumptech/glide
https://github.com/firebase/FirebaseUI-Android
https://allyourbase.hatenablog.com/entry/glide-binding-adapter