KotlinでAndroidアプリにRecyclerViewを実装する方法【ステップ別解説】
Kotlinを使ってAndroidアプリにRecyclerViewを実装する方法を、サンプルコード付きで段階的に解説します。本記事では、映画のリストをカード形式で一覧表示するシンプルなアプリを題材に、RecyclerViewの基本構造(レイアウト・アダプター・データモデル)の組み立て方を学ぶことができます。
ステップ1:新規プロジェクトを作成する
Android Studioを起動し、「File」→「New Project」から新しいプロジェクトを作成します。必要な項目をすべて入力して、プロジェクトの雛形を生成しましょう。
ステップ2:メインレイアウト(activity_main.xml)を編集する
res/layout/activity_main.xmlに以下のコードを記述します。画面全体にRecyclerViewを配置するシンプルな構成です。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:id="@+id/rlMain" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
ステップ3:MainActivity.ktを実装する
src/MainActivity.ktに以下のコードを追加します。LinearLayoutManagerとDefaultItemAnimatorを設定し、prepareMovieData()メソッドでリストに表示する映画データを準備しています。
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
private val movieList = ArrayList<MovieModel>()
private lateinit var moviesAdapter: MoviesAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
moviesAdapter = MoviesAdapter(movieList)
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView.layoutManager = layoutManager
recyclerView.itemAnimator = DefaultItemAnimator()
recyclerView.adapter = moviesAdapter
prepareMovieData()
}
private fun prepareMovieData() {
var movie = MovieModel("Mad Max: Fury Road", "Action & Adventure", "2015")
movieList.add(movie)
movie = MovieModel("Inside Out", "Animation, Kids & Family", "2015")
movieList.add(movie)
movie = MovieModel("Star Wars: Episode VII - The Force Awakens", "Action", "2015")
movieList.add(movie)
movie = MovieModel("Shaun the Sheep", "Animation", "2015")
movieList.add(movie)
movie = MovieModel("The Martian", "Science Fiction & Fantasy", "2015")
movieList.add(movie)
movie = MovieModel("Mission: Impossible Rogue Nation", "Action", "2015")
movieList.add(movie)
movie = MovieModel("Up", "Animation", "2009")
movieList.add(movie)
movie = MovieModel("Star Trek", "Science Fiction", "2009")
movieList.add(movie)
movie = MovieModel("The LEGO MovieModel", "Animation", "2014")
movieList.add(movie)
movie = MovieModel("Iron Man", "Action & Adventure", "2008")
movieList.add(movie)
movie = MovieModel("Aliens", "Science Fiction", "1986")
movieList.add(movie)
movie = MovieModel("Chicken Run", "Animation", "2000")
movieList.add(movie)
movie = MovieModel("Back to the Future", "Science Fiction", "1985")
movieList.add(movie)
movie = MovieModel("Raiders of the Lost Ark", "Action & Adventure", "1981")
movieList.add(movie)
movie = MovieModel("Goldfinger", "Action & Adventure", "1965")
movieList.add(movie)
movie = MovieModel("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014")
movieList.add(movie)
moviesAdapter.notifyDataSetChanged()
}
}
ステップ4:データモデル(MovieModel.kt)を作成する
新しいクラスファイルMovieModel.ktを作成し、以下のコードを追加します。タイトル・ジャンル・公開年の3つのプロパティを持つ、リスト項目用のデータクラスです。
class MovieModel(title: String?, genre: String?, year: String?) {
private var title: String
private var genre: String
private var year: String
init {
this.title = title!!
this.genre = genre!!
this.year = year!!
}
fun getTitle(): String? {
return title
}
fun setTitle(name: String?) {
title = name!!
}
fun getYear(): String? {
return year
}
fun setYear(year: String?) {
this.year = year!!
}
fun getGenre(): String? {
return genre
}
fun setGenre(genre: String?) {
this.genre = genre!!
}
}
ステップ5:アダプター(MoviesAdapter.kt)を作成する
新しいクラスファイルMoviesAdapter.ktを作成し、以下のコードを追加します。RecyclerView.Adapterを継承したアダプターで、ViewHolderパターンを使って各項目のViewを効率的に管理します。
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.NonNull
import androidx.recyclerview.widget.RecyclerView
internal class MoviesAdapter(private var moviesList: List<MovieModel>) :
RecyclerView.Adapter<MoviesAdapter.MyViewHolder>() {
internal inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var title: TextView = view.findViewById(R.id.title)
var year: TextView = view.findViewById(R.id.year)
var genre: TextView = view.findViewById(R.id.genre)
}
@NonNull
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.movie_list, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val movie = moviesList[position]
holder.title.text = movie.getTitle()
holder.genre.text = movie.getGenre()
holder.year.text = movie.getYear()
}
override fun getItemCount(): Int {
return moviesList.size
}
}
ステップ6:リスト項目のレイアウト(movie_list.xml)を作成する
レイアウトリソースファイルmovie_list.xmlを新規作成し、以下のコードを追加します。CardViewの中に、タイトル・公開年・ジャンルの3つのTextViewを配置しています。
※アダプター側でR.layout.movie_listを参照しているため、ファイル名は必ず「movie_list.xml」としてください。
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="100dp" android:layout_margin="8dp" app:cardBackgroundColor="@android:color/holo_red_dark"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_toStartOf="@+id/year" android:textColor="@android:color/white" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/year" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:textColor="@android:color/white" /> <TextView android:id="@+id/genre" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:textColor="@android:color/white" /> </RelativeLayout> </androidx.cardview.widget.CardView>
補足:依存関係の追加について
RecyclerViewやCardViewを使用する場合は、app/build.gradleに以下の依存関係が必要です。最近のAndroid Studioテンプレートでは自動的に含まれていることが多いですが、ビルドエラーが出る場合は確認してみてください。
implementation 'androidx.recyclerview:recyclerview:1.3.2' implementation 'androidx.cardview:cardview:1.0.0'
ステップ7:AndroidManifest.xmlを確認する
androidManifest.xmlには以下のコードを記述します。本サンプルでは特別な権限は不要で、MainActivityをランチャーアクティビティとして登録するだけです。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
アプリを実行して動作を確認しよう
それでは、アプリを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続しておいてください。Android Studioからアプリを起動するには、プロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコン
をクリックします。デバイス選択のダイアログで自分のモバイル端末を選択すると、端末上に以下のような映画リスト画面が表示されます。

-
【Android】GridLayoutManagerとRecyclerViewで作るシンプルなグリッド表示の実装例
RecyclerViewとは? GridLayoutManagerを使ったRecyclerViewのグリッド表示の例に入る前に、まずAndroidにおけるRecyclerViewとは何かをおさらいしておきましょう。RecyclerViewはListViewをさらに進化させた高度なコンポーネントで、ViewHolderデザインパターンに基づいて動作します。RecyclerViewを利用することで、グリッド形式やリスト形式のアイテムをメモリ効率よく表示できます。 本記事で作成するアプリ この記事では、学生の名前と年齢をグリッド状に表示する「学生記録アプリ」を題材に、RecyclerViewとGr
-
KotlinでAndroidアプリにフリングジェスチャ検出を実装する方法
KotlinでAndroidアプリにフリングジェスチャ検出を実装する方法 このチュートリアルでは、Kotlinを使用してAndroidアプリでフリング(fling)ジェスチャの検出を機能させる方法を、ステップごとにわかりやすく解説します。フリングジェスチャとは、指を画面上で素早く弾くように動かす操作のことで、リストの高速スクロールやページの切り替えなど、さまざまな場面で活用されています。 ステップ1: 新しいプロジェクトを作成する Android Studioで新しいプロジェクトを作成します。メニューから「File」⇒「New Project」を選択し、必要な項目をすべて入力してプロジェクトを