안드로이드 앱 개발

RecyclerView 아이템 간격 조절하기 본문

안드로이드앱/RecyclerView

RecyclerView 아이템 간격 조절하기

스텝바이스텝안드로이드 2021. 3. 26. 01:06

1. 구분선 추가

리사이클러뷰를 사용하는 자바소스에 아래 소스만 추가

DividerItemDecoration dividerDecoration = 
new DividerDecoration(recyclerView.getContext(), new LinearLayoutManager(this).getOrientation());

recyclerView.addItemDecoration(dividerDecoration);

 

2. 간격추가

 

2-1 height

 

아래와 같은 자바 클래스 생성

public class RecyclerDecoration_Height extends RecyclerView.ItemDecoration {
    private final int divHeight;

    public RecyclerDecoration_Height(int divHeight){
        this.divHeight = divHeight;
    }


    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if (parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount() - 1){
            outRect.bottom = divHeight;
        }
    }

}

 

그 다음 리사이클러뷰를 사용하는 자바소스에 적용 

 RecyclerDecoration_Height decoration_height = new RecyclerDecoration_Height(20);
        recyclerView.addItemDecoration(decoration_height);

 

2-2 width

public class RecyclerViewDecoration extends RecyclerView.ItemDecoration {

    private final int divWidth;

    public RecyclerViewDecoration(int divWidth)
    {
        this.divWidth = divWidth;
    }

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