1

I have a RecyclerView and want to set the text and change the visibility of a TextView when the user is scrolling. The View should show for a second after the user stopped scrolling and then disaper. For that I have a RecyclerView.OnScrollListener. My Code looks something like this:

var scrollJob = Job()
var tempText = ""

recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        if (dx != 0 || dy != 0) {
            val someText = // compute text from ViewHolder
            scrollTextView.visibility = View.VISIBLE
            if (someText != tempText) {
                scrollTextView.text = someText
                tempText = someText
            }
        }
    }

    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        when (newState) {
            RecyclerView.SCROLL_STATE_SETTLING -> Log.d("TAG", "state: settling")
            RecyclerView.SCROLL_STATE_IDLE -> {
                scrollJob.cancel()
                scrollJob = lifecycleScope.launch {
                    delay(1000)
                    scrollTextView.visibility = View.GONE
                }
            }
            RecyclerView.SCROLL_STATE_DRAGGING -> scrollJob.cancel()
        }
    }
}

The code is running completly fine, I'm just wondering if I shouldn't do that many things in onScrolled since older phones might have problems with this. The problem with SCROLL_STATE_DRAGGING is that it is called even if it isn't desired.

msimic
  • 76
  • 4

1 Answers1

0

Propably u need get the visibility of scrollTextView, and if INVISIBLE or GONE, u will make it VISIBLE. U dont need make it VISIBLE if already VISIBLE...

if (scrollTextView.getVisibility() != View.VISIBLE)
scrollTextView.visibility = View.VISIBLE

Make the same in every case, this will peform ur performance!

  • 1
    According to [this answer](https://stackoverflow.com/a/15164976/11606076) checking visibility is unnecessary. – msimic Apr 26 '21 at 15:59