smoothScrollToPositionFromTop() is not always working like it should

前端 未结 5 636
失恋的感觉
失恋的感觉 2020-11-27 15:26

I\'ve been trying for a while to get smoothScrollToPositionFromTop() working, but it doesn\'t always scroll to the correct position.

I\'ve got a ListView (with 10 i

5条回答
  •  再見小時候
    2020-11-27 15:55

    Here is Lars Blumberg answer in Kotlin including dira's comment, it is working for me.

    private fun smoothScrollToPositionFromTop(listView: AbsListView, position: Int, offset: Int) {
    
        listView.setOnScrollListener(object : AbsListView.OnScrollListener {
    
            override fun onScroll(
                view: AbsListView?,
                firstVisibleItem: Int,
                visibleItemCount: Int,
                totalItemCount: Int
            ) { }
    
            override fun onScrollStateChanged(view: AbsListView?, scrollState: Int) {
                view?.setOnScrollListener(null)
    
                // Fix for scrolling bug.
                if (scrollState == SCROLL_STATE_IDLE) {
                    Handler(Looper.getMainLooper()).post {
                        listView.setSelectionFromTop(position, offset)
                    }
                }
            }
        })
    
        // Perform scrolling to position
        Handler(Looper.getMainLooper()).post {
            listView.smoothScrollToPositionFromTop(position, offset)
        }
    }
    

提交回复
热议问题