[Android] GridLayout에 각각 아이템별 간격조절하기

MJ·2023년 3월 17일
2

Android

목록 보기
6/8
post-thumbnail

RecyclerView에서 GridLayout을 하게되면 각 아이템이 간격없이 나타난다.
그래서 따로 간격조정을 해줘야 한다.

GridSpaceItemDecoration

class GridSpaceItemDecoration(private val spanCount: Int, private val space: Int) :
    RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val position = parent.getChildAdapterPosition(view)
        val column = position % spanCount + 1      // 1부터 시작

        // 첫 행 제외하고 상단 여백 추가
        if (position >= spanCount) {
            outRect.top = space
        }
        outRect.bottom = space
        // 첫번째 열을 제외하고 좌측 여백 추가
        if (column != 1) {
            outRect.left = space
        }
    }
}

MainActivvity

override fun onCreate(savedInstanceState: Bundle?) {
	super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
	val recyclerView = findViewById<RecyclerView>(R.id.rv_list)

    gridadapter = GridItemAdapter()
    recyclerView?.adapter = gridadapter
    recyclerView?.run {
        val spanCount = 2
        val space = 20 //20dp로 간격 지정
        addItemDecoration(GridSpaceItemDecoration(spanCount, space))
    }
}

결과화면

before

after

소스코드

Github

0개의 댓글