okuzawatsの日記

Android / Kotlin / GitHub Actions Enthusiast 🤖

[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を明示的に指定するには、 orientationverticalhorizontal を指定します。以下は 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

書いている人 😎

profile

茨城県つくば市在住のモバイルアプリケーションアーキテクト(Androidが得意です)。モバイルアプリのアーキテクチャ、自動テスト、CI/CDに興味があります。いわゆる「レガシーコード」のリファクタリング・リアーキテクチャが好きです。

👉 もっと詳しく

著書 ✍

Android 依存性注入 ヒッチハイク・ガイド🧳

Androidアプリでの依存性注入(Dependency Injection)に入門するためのガイダンスです。依存性注入の概念やメリットを理解し、Dagger Hiltを用いてAndroidアプリに適用する方法を解説しています。

販売サイトへ🏃

ソフトウェアデザイン 2023年6月号📚

特集「クリーンアーキテクチャとは何か?」の第5章「モバイルアプリ開発における実践」を執筆しました。

販売サイトへ🏃

Android クリーンアーキテクチャ ヒッチハイク・ガイド🧳

Androidアプリでのクリーンアーキテクチャに入門するためのガイダンスです。クリーンアーキテクチャの概念を理解し、Androidアプリに適用する方法を解説しています。

販売サイトへ🏃

Android ユニットテスト ヒッチハイク・ガイド🧳

Androidアプリのユニットテストに入門するためのガイダンスです。初学者が混乱せずにAndroidアプリのユニットテストを書き始めることができる、ということを目的としています。

販売サイトへ🏃

Android MVVMアーキテクチャ入門🛠

Androidアプリ開発の初学者に向けた、MVVM(Model-View-ViewModel)アーキテクチャの入門書を書きました。初学者の方を確実にネクストレベルに引き上げる技術書です。NextPublishingより出版されています。

販売サイトへ🏃

関連記事 👀

お問い合わせ✉️

Androidアプリ開発、特にレガシープロジェクトに関するご相談はこちらまで📨

お名前

メールアドレス

お問い合わせ内容