5
5

More than 1 year has passed since last update.

RecyclerViewのいつもの設定をXMLでスマートに設定する方法

Posted at

はじめに

歴史のあるプロジェクトでは大体LayoutManagerの設定などをkotlinで指定しているのをよく見かけます。
この辺りはxmlでも設定ができるので、紹介したいと思います。

LinearLayoutManagerを設定する場合

LinearLayoutManagerを設定する場合は以下をxmlに設定します。

<androidx.recyclerview.widget.RecyclerView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>

設定は以上です。
LinearLayoutManagerのみの設定でも問題ありませんが、スクロール方向をorientationで設定できるので、こちらを設定してあげると親切ですね。

GridLayoutManagerを設定する場合

GridLayoutManagerを設定する場合は以下をxmlに設定します。

<androidx.recyclerview.widget.RecyclerView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
            app:spanCount="1"/>

GridLayoutManagerの場合はspanCountを合わせて設定する必要があります。
LinearLayoutManagerと同様にorientationを設定することでスクロール方向を指定できますので、設定してあげると良いかと思います。

おまけ

dividerを設定したいケースがあると思います。
そんな時は以下のようなBindingAdapterを設定しておくと簡単に設定できるようになります。

@BindingAdapter("hasDivider")
fun RecyclerView.setDivider(hasDivider: Boolean) {
    val layoutManager = this.layoutManager
    if (hasDivider && itemDecorationCount == 0) {
        addItemDecoration(DividerItemDecoration(context, RecyclerView.VERTICAL))
    }
}

ちなみに設定できるのは縦方向のスクロールの場合のみです。
check関数などで正しい設定が行われている状態で呼び出されているかチェックしてあげても良いと思います。

さいごに

ご存知の方も多い設定かもしれませんが、意外とkotlin側で設定されていること多かったりしますよね。
ほんの数行の違いかもしれませんが、Fragmentが綺麗だとスッキリしますので、まだFragmentで設定しているよ、という方は是非試してみていただければと思います。

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