RecyclerVIew auto scroll to display all the elements as in News Feed etc.,

前端 未结 7 721
慢半拍i
慢半拍i 2020-12-14 11:47

How to auto scroll RecyclerView smoothly so that user can see all the elements of the RecyclerView and scroll again from the start - as in News Feed etc.

<
7条回答
  •  温柔的废话
    2020-12-14 12:33

    Simplified in Kotlin:

     lifecycleScope.launch(Dispatchers.Main, start = CoroutineStart.DEFAULT) {
            var position = MINIMUM_POSITION
            repeat(AUTO_SCROLL_REPEATING_TIMES) {
                delay(SCROLL_DELAY)
                rvBanners.smoothScrollToPosition(position)
                when {
                    position+1 == listSize -> position = 0
                    position == 0 -> position = MINIMUM_POSITION
                    else -> position++
                }
            }
        }
    

    If you want to start the auto-scroll at a specific time:

    val job = lifecycleScope.launch(Dispatchers.Main, start = CoroutineStart.LAZY) {
            var position = MINIMUM_POSITION
            repeat(AUTO_SCROLL_REPEATING_TIMES) {
                delay(SCROLL_DELAY)
                rvBanners.smoothScrollToPosition(position)
                when {
                    position+1 == listSize -> position = 0
                    position == 0 -> position = MINIMUM_POSITION
                    else -> position++
                }
            }
        }
    ...
    job.start()
    

提交回复
热议问题