LoginSignup
4
4

More than 3 years have passed since last update.

RecyclerViewにサムネイルを表示する

Posted at

RecyclerViewにネットから取得した画像を表示する方法を纏めます。

画像のキャッシュにglideを使うことで簡単に表示することができました(下記参照)。
https://developer.android.com/topic/performance/graphics/cache-bitmap?hl=ja

サンプルコード

依存ライブラリにglideを追加します。

build.gradle
dependencies {
    implementation "com.github.bumptech.glide:glide:4.11.0"
}

使い方は簡単でItem内に配置したImageViewに対して、
Glide.with(context).load("https://xxxx").into(holder.imageView)
と記載するだけです。

ListAdapter.kt
class ListAdapter (private val context: Context) : RecyclerView.Adapter<ListAdapter.ListAdapterHolder>() {
    private val inflater = LayoutInflater.from(context)

    class ListAdapterHolder(view: View) : RecyclerView.ViewHolder(view) {
        var textView: TextView = view.findViewById(R.id.text)
        var imageView: ImageView = view.findViewById(R.id.image)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListAdapterHolder {
        val view = inflater.inflate(R.layout.list_item, parent, false)
        return ListAdapterHolder(view)
    }

    override fun getItemCount(): Int {
        return 100
    }

    override fun onBindViewHolder(holder: ListAdapterHolder, position: Int) {
        holder.textView.text = "image ${position + 1}"
        Glide.with(context).load("https://xxxx").into(holder.imageView)
    }
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listItem"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:focusable="true"
    android:clickable="true">

    <ImageView
        android:id="@+id/image"
        android:layout_gravity="center"
        android:layout_width="50dp"
        android:layout_height="wrap_content" />

    ...
</LinearLayout>

補足

単純に画像を取得するだけでなく、処理(ハッシュチェックなど)が必要な場合は、ModelLoaderを作成することで処理が行えます。
ModelLoaderについては、下記参照。
https://bumptech.github.io/glide/tut/custom-modelloader.html

Kotlinで実装する場合は、下記も参照。
https://bumptech.github.io/glide/doc/download-setup.html#kotlin

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