How to show "Toast" after scrolling down a certain amount in Kotlin

Viewed 250

I want to implement a feature in my app where it shows a Toast/message when a user scrolls down the recyclerview. For example when the user is scrolling down the screen, after they pass about 10 items a Toast pops up saying "Tap the home button to go back to the top"

How would I go about doing this?

2 Answers

I don't know if this would work, but you can try doing it in your adapter. like

when (position) {
      10 -> Toast.makeText().show
}

or use an if statment. Again, I don't know for sure if it would work, but I think so.

I think it's probably preferable to base it on distance scrolled instead of which item has appeared on screen most recently, so the threshold for when the message should be shown is not dependent on screen size. It's also best to keep this behavior out of the Adapter because of separation of concerns.

Here's a scroll listener you could use to do this behavior. I think the code is self-explanatory.

open class OnScrolledDownListener(
    private val context: Context,
    private val thresholdDp: Int,
    var resetOnReturnToTop: Boolean = true
): RecyclerView.OnScrollListener() {
    private var eventFired = false
    private var y = 0

    open fun onScrolledDown() {}
    open fun onScrolledBackToTop() {}
    
    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        y += dy
        val yDp = (y / context.resources.displayMetrics.density).roundToInt()
        if (yDp >= thresholdDp && !eventFired) {
            eventFired = true
            onScrolledDown()
        } else if (resetOnReturnToTop && yDp == 0 && eventFired) {
            eventFired = false
            onScrolledBackToTop()
        }
    }
}

You can subclass and override the two events for when it scrolls down at least a certain amount for the first time (onScrolledDown), and for when it is scrolled back to the top and resets itself (onScrolledBackToTop).

myRecyclerView.addOnScrollListener(object: OnScrolledDownListener(context, 120) {
    override fun onScrolledDown() {
        showMyMessage()
    }

    override fun onScrolledBackToTop() {
        hideTheMessage()
    }
})
Related