9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RecyclerViewのdividerをDataBindingで設定する

Last updated at Posted at 2016-06-09

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>
9
8
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
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?