[Android] RecyclerViewのLayoutManagerをxmlで指定する
RecyclerViewのLayoutManagerをKotlin / Javaのコードで指定しているケースを散見しますが、RecyclerViewのLayoutManagerはxml側でも定義できます。個人的には、LayoutManagerをxml側で定義した方がロジックとレイアウトを分離できて良いと感じています。
xml側でRecyclerViewのLayoutManagerを指定する方法は、以下のように app:layoutManager
にLayoutManagerを指定します。
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
上記の例ではLayoutManagerにLinearLayoutManagerを指定しています。LinearLayoutManagerは、Orientationに縦か横のどちらかを指定できます。デフォルトのOrientationは縦ですので、特に指定がなければ縦に要素が並びます。LinearLayoutManagerのOrientationを明示的に指定するには、 orientation
に vertical
か horizontal
を指定します。以下は vertical
の例です。
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
LayoutManagerにGridLayoutManagerを指定する場合、一行あたりのセルの数は、 spanCount
で指定できます。以下は spanCount
として2を指定する例です。
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:spanCount="2"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"/>
書いている人 😎

茨城県つくば市在住のモバイルアプリケーションアーキテクト(Androidが得意です)。モバイルアプリのアーキテクチャ、自動テスト、CI/CDに興味があります。いわゆる「レガシーコード」のリファクタリング・リアーキテクチャが好きです。
👉 もっと詳しく
著書 ✍
Android クリーンアーキテクチャ ヒッチハイク・ガイド 🧳
Androidアプリでのクリーンアーキテクチャに入門するためのガイダンスです。クリーンアーキテクチャの概念を理解し、Androidアプリに適用する方法を解説しています。
Android ユニットテスト ヒッチハイク・ガイド 🧳
Androidアプリのユニットテストに入門するためのガイダンスです。初学者が混乱せずにAndroidアプリのユニットテストを書き始めることができる、ということを目的としています。
Android MVVMアーキテクチャ入門 🛠
Androidアプリ開発の初学者に向けた、MVVM(Model-View-ViewModel)アーキテクチャの入門書を書きました。初学者の方を確実にネクストレベルに引き上げる技術書です。NextPublishingより出版されています。
関連記事 👀
- DroidKaigi.collect{ #1@Tokyo }で「例外を投げるな、値を返せ」というLTをしました
- Truthのカスタムサブジェクトを定義する
- [Android] build.gradle.ktsでJaCoCoを動かす
- [Android] EventBusの思い出🚌
- [Android] Clean Architecture の理論と実装