RecyclerViewのdividerをDataBindingで設定する

  • 8
    Like
  • 0
    Comment
More than 1 year has passed since last update.

DataBindingのカスタムBindingAdapterを使って楽する。

都合の良いItemDecorationを用意する

DividerDecoration.java
public class DividerDecoration extends RecyclerView.ItemDecoration {

    private Drawable mDivider;

    public DividerDecoration(Drawable drawable) {
        mDivider = drawable;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
    }
}

カスタムBindingAdapterを定義する

RecyclerViewBindingAdapter.java
public class RecyclerViewBindingAdapter {

    @BindingAdapter("dividerDrawable")
    public static void setDividerDrawable(RecyclerView recyclerView, Drawable drawable) {
        recyclerView.addItemDecoration(new DividerDecoration(drawable));
    }
}

XMLで指定する

activity_main.xml
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager"
        app:dividerDrawable="@{@drawable/divider}"/>

</layout>
drawable/divider.xml
<shape
    xmlns:android="http://schemas.android.com/apk/res/android">

    <size android:height="1dp"/>
    <solid android:color="@color/divider_color"/>

</shape>