出现这个问题的原因是在使用ReversedGridLayoutManager转换方向时,item的宽度没有被正确计算,导致出现空白的区域。解决这个问题的方法如下:
class CustomGridLayoutManager(context: Context, spanCount: Int) : GridLayoutManager(context, spanCount) {
override fun getDecoratedMeasuredWidth(child: View): Int {
val lp = child.layoutParams as RecyclerView.LayoutParams
val spanSize = lp.spanSize
val spanCount = spanCount
val width = recyclerView?.width ?: 0
val itemWidth = (width - (spanCount - spanSize)) / spanSize
return super.getDecoratedMeasuredWidth(child).coerceAtMost(itemWidth)
}
}
val layoutManager = CustomGridLayoutManager(this, SPAN_COUNT) recyclerView.layoutManager = layoutManager
这样就能正确计算item的宽度,避免出现空白的区域了。