我有一个recyclerView
,希望在用户滚动时设置文本并更改TextView
的可见性。在用户停止滚动后,视图
应该显示一秒钟,然后停止。为此,我有一个RecyclerView.onScrollListener
。我的代码如下所示:
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()
}
}
}
代码运行得很好,我只是在想,如果我不应该在onscrold
中做那么多事情,因为旧的手机可能会有这样的问题。scroll_state_dragging
的问题是,即使不需要也会调用它。
当然,您需要获得scrollTextView的可见性,如果不可见或消失,您将使它可见。如果已经可见,则不需要使其可见...
if (scrollTextView.getVisibility() != View.VISIBLE)
scrollTextView.visibility = View.VISIBLE
在每种情况下都做同样的,这将改善你的表现!