3 回答

TA貢獻1851條經驗 獲得超3個贊
該錯誤是由于負索引 (-1) 造成的。
看這段代碼:
if (count == headerSliderAdapter.getItemCount() - 1) {
flag = false;
} else if (count == 0) {
flag = true;
}
如果您的項目數為 1,那么第一個項目if將true在 時出現count == 0。1 - 1 = 0 所以flag = false。
然后,當你到達第二個時if:
if (flag) count++;
else count--;
flag是false這樣你的代碼將執行count--但count已經是 0,因此你得到count == -1.
然后你嘗試滾動到負位置,這是不允許的。

TA貢獻1883條經驗 獲得超3個贊
不要使用非線程安全的延遲后方法。
private fun scrollToLastItem(view: View) {
//pos.coerceAtLeast(0) // Use this
view.recycler_view.smoothScrollToPosition(pos.coerceAtLeast(0))
}
RCA:在 ScrollLayoutManager startSmoothPendingScroll 方法崩潰之前,當前位置為 -1。

TA貢獻1865條經驗 獲得超7個贊
它也可以(在最后一個位置的情況下):
private fun scrollToLastItem(view: View) {
adapter.itemCount.takeIf { it > 0 }?.let {
view.recycler_view.smoothScrollToPosition(it - 1)
}
}
添加回答
舉報