1
1

More than 3 years have passed since last update.

AndroidでDataBindingを使ってFirebase Storageから画像を読み込む方法です。
Glideも一緒に使います。Kotlinで書いています。

セットアップ

FirebaseとDataBindingのセットアップは割愛します。

Glide

KotlinでGlideを使う場合は、

app/build.gradle
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を継承したクラスを作成します。

MyAppGlideModule.kt

@GlideModule
class MyAppGlideModule : AppGlideModule() {

}

これで、自動的にGlideAppが使えるようになります。

Firebase Storage UI

通常のFirebaseに加え、Firebase UIも追加します。

app/build.gradle
dependencies {
    implementation 'com.firebaseui:firebase-ui-storage:7.1.1'
}

GlideでFirebase Storageの読み込み

Glideそのままでは、Firebase Storageの読み込みに対応していないので、StorageReferenceを読み込めるようにします。

app/build.gradle
@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に画像を読み込み

データモデルは

Image.kt
data class Image(val path: String)

pathはFirebase Storageのパスとします。

DataBindingを使い、GlideからImageViewで読み込むためには、

ImageBindingAdapter.kt
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レイアウトファイルで以下のように記述します

layout.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

1
1
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
1
1