코딩스토리

[Android/안드로이드] RecyclerView ItemDecoration으로 아이템 항목 구분지어주기 본문

Android/유용한 기술

[Android/안드로이드] RecyclerView ItemDecoration으로 아이템 항목 구분지어주기

라크라꾸 2020. 9. 12. 17:29

앱을 구현할 때 디자인에 따라 마지막 아이템만 구분선이 없거나 첫번째 아이템만 구분선이 있는 등 각 항목마다 구분을 지어줄 필요가 있는 디자인이 있습니다. 

 

ItemDecoration을 잘만 사용하게 되면 다양하게 항목을 꾸밀 수 있습니다. ItemDecoration에는 3개의 함수를 제공해주고있습니다.

 

  • onDraw : 항목을 배치하기 전에 호출합니다
  • onDrawOver : 모든 항목이 배치된 후에 호출됩니다.
  • onItemOffsets : 각 항목을 배치할 때 호출됩니다.

우선 구분선을 만들어준 drawable파일을 만들어보겠습니다.

 

line_divider.xml

	
    <?xml version="1.0" encoding="utf-8"?>
	<shape xmlns:android="http://schemas.android.com/apk/res/android"
	    android:shape="rectangle">
	    <size
	        android:width="1dp"
	        android:height="1dp" />
	    <solid android:color="#000000" />
	</shape>
	

 

MyItemDecoration.java

package com.lakue.recyclerviewmanager;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class MyItemDecoration extends RecyclerView.ItemDecoration {
    Context context;
    Drawable mDivider;

    public MyItemDecoration(Context context) {
        this.context = context;

        mDivider = context.getResources().getDrawable(R.drawable.line_divider);
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.bottom = 100;
    }

    @Override
    public void onDrawOver(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDrawOver(c, parent, state);

        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();

        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
}

 

이제 RecyclerView에 적용을 하면 각 항목마다 구분선을 넣어집니다.

 

	
    recyclerView.addItemDecoration(new MyItemDecoration(this));
    

 

Comments