Kotlin は、ListViewというView(データ表示機能)を使用することで、簡単に配列やリストを一覧表示させるUI部品で、料理アプリやニュースアプリなどにも用いられています。
本記事では、そんな ListView を Kotlin で実装する方法について、サンプルコードを交えながら解説します。
リストビューとは
リストビューを知らない人に簡単に説明すると、アイテム一覧といったページを作りたい時に便利な仕組みです。
手動で1つずつレイアウトを作ることもできますが、運用視点において改修が容易になるなど、利点が多くありますので、是非とも使ってみてください。
ListViewの4要素
リスト表示は、複数の要素で構成されています。
- <ListView>タグを実装する
テキストや画像といった素材。 - データ
一覧表示するデータ。配列で保持します。 - リストレイアウト
1行なのか、2行なのかというような仕様を決めます。
androidスタジオに備わっているものがありますが、自作も可能です。 - アダプタで内部処理を実行する
ListViewやレイアウト、データといった要素をアダプタにまとめてから表示させます。
それでは実装内容です。
この記事の対象者
・縦並びの同一レイアウトを素早く作りたい方
・AndroidStudio で Kotlin アプリを開発している方
・リストビューを使う必要があり、コピペでとりあえず実装したい方
所要時間
15分
ソースコード
ソースコードを github で公開しています。
よければこちらも参考にご利用ください。
実装内容
データクラスの作成(リスト一行に表示するデータ)
データクラスを作成します。
1 2 3 4 5 |
data class Data( var icon: ImageView? = null, var title: String? = null, var text: String? = null ) |
Dataというクラスを作成し、画像(icon)、タイトル(title)、文書(text)をパラメータに持つように実装しました。
リスト一行分のレイアウトを作成
id 属性を指定します。(11,20,31行目)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="72dp" android:paddingStart="16dp" android:paddingEnd="16dp" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" > <ImageView android:id="@+id/user_icon" android:layout_width="72dp" android:layout_height="72dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" android:src="@android:drawable/ic_menu_gallery" android:contentDescription="" /> <TextView android:id="@+id/title" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintBottom_toTopOf="@+id/text" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@id/user_icon" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_chainStyle="packed" tools:text="Title" /> <TextView android:id="@+id/text" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@id/user_icon" app:layout_constraintTop_toBottomOf="@id/title" tools:text="asdadsadjasdadadasadsasdasdasda" /> </androidx.constraintlayout.widget.ConstraintLayout> |
※このレイアウトが一行分のレイアウトになるので、変更することによってビューのカスタマイズが可能です。
カスタムアダプターの作成
カスタムアダプタを作成します。getViewメソッドでは、各項目のレイアウトを設定します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class CustomAdapter(context: Context, list: ArrayList<Data>) : ArrayAdapter<Data>(context, 0, list) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var view = convertView if (view == null) { // 一行分のレイアウトを生成 view = LayoutInflater.from(context).inflate(R.layout.row_view, parent, false) } // 一行分のデータを取得 val data = getItem(position) // 一行分のレイアウトに取得したdataの情報をセットする view?.findViewById<ImageView>(R.id.user_icon).apply { data?.icon } view?.findViewById<ImageView>(R.id.title).apply { data?.title } view?.findViewById<ImageView>(R.id.text).apply { data?.text } return view!! } } |
アクティビティのxmlファイルにリストビューを追加
xml を生成し、リストビューを追加します。
<ListView/>タグで ListView を実装します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/Theme.Practice.AppBarOverlay"> </com.google.android.material.appbar.AppBarLayout> <!--こちらを追加--> <ListView android:id="@+id/custom_list_view" android:layout_width="match_parent" android:layout_height="wrap_content" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> |
アクティビティへアダプタをセットする
ArrayAdapter を生成し、ListView に設定します。
ArrayAdapter は、配列やリストを1つずつ表示する際に使うアダプタです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // リストデータの作成 val dataList = arrayListOf<Data>() for (i in 0..100){ dataList.add(Data().apply { title = "${i}番目のタイトル" text = "${i}番目のテキスト" }) } // アダプターをセット val adapter = CustomAdapter(this, dataList) custom_list_view.adapter = adapter } } |
より深く理解するために
リストビューの表示に成功した方は、データクラスに年齢という変数を追加して、ビューをカスタマイズして表示してみましょう。
時間ができたらお試しいただくとより深く理解できるかと思います。
1 2 3 4 5 6 |
data class Data( var icon: ImageView? = null, var title: String? = null, var text: String? = null, var age: Int? = null ) |
まとめ
リストビューは基本の View class で出来ることの殆どが効率的に実装できます。
また、本記事のような生成に必要な処理をコピペで使えるようにしておくことで楽に実装ができるのも良いところですね。
次のステップとしてタッチイベント等もセットしてみると実際の実装イメージに近いものも出来ると思いますので、是非試してみてください。