Handler.postdelay()在滚动状态更改时在回收器视图中不起作用

时间:2019-05-27 06:00:41

标签: android kotlin android-recyclerview android-handler onscrolllistener

我基本上是在RecyclerView内的scroll state change内尝试执行一个方法,这里我使用Handler线程在经过一段时间延迟后执行一个方法,但是该方法不是完全可以执行,但是如果我将该方法放到处理程序线程之外,它将成功执行,所以我的问题是为什么我无法在Handler RecyclerView内运行onscroll线程,这是我的代码请看看。

rvsongs!!.addOnScrollListener(object: RecyclerView.OnScrollListener(){
                override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if(newState== SCROLL_STATE_IDLE) {
                    val timerHandler = Handler()
                    var updater:Runnable?=null
                    updater = object:Runnable {
                        override fun run() {
                            rvsongs!!.setIndexBarVisibility(false)//this method is not getting executed however when put outside handler thread it's executed without any problem
                        }
                    }
                    timerHandler.postDelayed(updater,100)
                }
                else
                {
                    rvsongs!!.setIndexBarVisibility(true)
                }
            }
        })

1 个答案:

答案 0 :(得分:1)

问题是您要在处理完整的setIndexBarVisibilty之后调用onScrollStateChanged。换句话说,recyclerViewsetIndexBatVisibility之前呈现。

要解决此问题,只需在invalidate之后致电setIndexBarVisibility

       ...
       var updater:Runnable?=null
        updater = object:Runnable {
            override fun run() {
                rvsongs!!.setIndexBarVisibility(false)
                rvsongs.invalidate()
            }
        }
        ...