개발일지

Android in A..Z - RecyclerView (SnapHelper) 본문

Android (안드로이드)/RecyclerView

Android in A..Z - RecyclerView (SnapHelper)

강태종 2021. 1. 21. 23:13

SnapHelper

RecyclerView를 ViewPager처럼 사용하거나 NumberPicker처럼 Scroll하다가 하나의 Item을 자석처럼 끌어당겨 하나의 Item을 선택하게 도와주는 클래스이다.


Kotlin

val snapHelper = LinearSnapHelper()
snapHelper.attachToRecyclerView(recyclerView)

OnScrollListener를 사용해서 SnapHelper가 선택한 position 받기

recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
    var currentPosition = RecyclerView.NO_POSITION

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        if (recyclerView.layoutManager != null) {
            val view = snapHelper.findSnapView(recyclerView.layoutManager)!!
            val position = recyclerView.layoutManager!!.getPosition(view)

            if (currentPosition != position) {
                currentPosition = position
                binding.position = currentPosition
            }
        }
    }
})

Git (예제코드)

github.com/KangTaeJong98/Example/tree/main/Android/RecyclerView

 

KangTaeJong98/Example

My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.

github.com

 

Comments