object RecyclerViewHelper { /** * RecyclerView 注册加载更多监听 */ @JvmStatic funaddOnScrollListener(recyclerView: RecyclerView, loadMore: () -> Unit) { recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { overridefunonScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == RecyclerView.SCROLL_STATE_IDLE) { val layoutManager = recyclerView.layoutManager if (layoutManager is LinearLayoutManager) { val lastPosition = layoutManager.findLastCompletelyVisibleItemPosition() val count = layoutManager.itemCount if (lastPosition >= count - 2) { loadMore() return@onScrollStateChanged } } elseif (layoutManager is StaggeredGridLayoutManager) { val spanCount = layoutManager.spanCount val count = layoutManager.itemCount val result = IntArray(spanCount) layoutManager.findLastCompletelyVisibleItemPositions(result) for (it in result) { if (it >= count - spanCount - 1) { loadMore() return@onScrollStateChanged } } } elseif (layoutManager is GridLayoutManager) { val spanCount = layoutManager.spanCount val count = layoutManager.itemCount val lastPosition = layoutManager.findLastCompletelyVisibleItemPosition() if (lastPosition >= count - spanCount - 1) { loadMore() return@onScrollStateChanged }
} } } }) }
/** * 判断是否一屏显示 * * 错误或者空了返回 false */ @JvmStatic funisOneScreen(recyclerView: RecyclerView?): Boolean { recyclerView?.let { val layoutManager = recyclerView.layoutManager if (layoutManager is LinearLayoutManager) { // include GridLayoutManager val count = layoutManager.itemCount return count > 0 && layoutManager.findFirstCompletelyVisibleItemPosition() == 0 && layoutManager.findLastCompletelyVisibleItemPosition() == count - 1 } elseif (layoutManager is StaggeredGridLayoutManager) { val spanCount = layoutManager.spanCount val count = layoutManager.itemCount val last = IntArray(spanCount) val first = IntArray(spanCount) layoutManager.findLastCompletelyVisibleItemPositions(last) layoutManager.findFirstCompletelyVisibleItemPositions(first) return count > 0 && first.min() == 0 && last.max() == count - 1 } }
returnfalse }
privatefun IntArray.min(): Int { if (this.isNotEmpty()) { var result = this[0] this.forEach { if (result > it) result = it } return result } return -1 }
privatefun IntArray.max(): Int { if (this.isNotEmpty()) { var result = this[0] this.forEach { if (result < it) result = it } return result } return -1 } }