我的GridLayoutManager需要一些帮助。
如果我有一个项目,它应该在中间正常显示。
对于两个项目,这些项目应该彼此相邻。
Example with 2 Items
从三到四个项目应显示为正方形。
Example with 3 Items
Example with 4 Items
如果我是对的,那么spanCount 2就是这种情况。但是,如果有5个项目(所以连续三项),那就成问题了
五个项目(及以上)应连续三个
Example with 5 Items
如果最下面一行的项目也位于中间,那将特别好
我希望有人能帮助我,并提前感谢
最佳答案
您可以通过子类化GridLayoutManager
来动态设置跨度,如下所示:
class CustomGridLayoutManager(context: Context) : GridLayoutManager(context, 2) {
override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
updateSpanCount()
super.onLayoutChildren(recycler, state)
}
private fun updateSpanCount() {
val colCount = if (childCount <= 4) {
2
} else {
3
}
this.spanCount = colCount
}
}
如果要在最后一行中居中放置元素,则通过
GridLayoutManager
进行操作会有些麻烦。为此,您可能需要检查FlexboxLayout。这是由Google自己制作的库,具有HTML5 / CSS世界中常见的flex box模型。关于java - RecyclerView GridLayoutManager:每个项目计数的单独布局,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57618002/