89
87

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で行間に区切り線を表示する

Last updated at Posted at 2014-10-25

こんにちは
@wasabeef_jp です

引用:http://wasabeef.jp/recyclerview-itemdecoration/

近年、ListView2といわれるRecyclerViewを使うことが増えてくると思います
ListViewでは、下記のようにListViewを定義するxmlで区切り線(divider)の
設定が安易にできると思います

android:divider="#000000"
android:dividerHeight="2sp"

RecyclerViewでは、xmlで定義するのではなく
Java側で設定する必要があるので、その簡単なtipsをご紹介します。

RecyclerViewをそのまま使うと、下記のような区切り線(divider)が無いリストになります
xrecyclerview_divier1.png.pagespeed.ic.gh7fvrCQXv.png

そこで、登場するのがRecyclerView.ItemDecorationです。
RecyclerView.ItemDecorationを継承した自作のクラスを定義し
onDrawで、dividerを描画してあげると綺麗に表示されます。

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };

    private Drawable mDivider;

    public DividerItemDecoration(Context context) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        drawVertical(c, parent);
    }

    public void drawVertical(Canvas c, RecyclerView parent) {
        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());
    }
}

定義した自作クラスをaddItemDecorationで追加してあげると

mRecyclerView.addItemDecoration(new DividerItemDecoration(context));

こんな感じで表示されます。

xrecyclerview_divier2.png.pagespeed.ic.jV90of19X-.png

雑感

簡単なDividerを表示する場合は、ListViewより手間になるのですが
奇数偶数でDividerの表示を変えたり、点線のDividerを追加するなど自由度が高くなりました。

89
87
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
89
87

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?