使用不同的权重和大小无法正确绘制加权网格布局

我正在尝试使用网格布局(作为recyclerview的布局管理器)。对于某些物品,我希望有重量。

当项目重量等于列号时,它可以正常工作。但是当它小于它时,那是奇怪的。例如如果GridLayoutManager中的列数为3,并且我将第一项设置为权重3,则看起来像这样:

使用不同的权重和大小无法正确绘制加权网格布局

现在,如果具有相同的列数(3),我将第一项的权重设置为2,则它看起来像这样:

使用不同的权重和大小无法正确绘制加权网格布局

我该如何解决?

此外,我为项目之间的间距定义了项目装饰,而且看起来也没有对齐:

使用不同的权重和大小无法正确绘制加权网格布局

有什么想法要解决吗?

我的代码:

val columns = 3
    val recyclerViewLayoutManager = GridLayoutManager(context,columns) .apply {
        orientation = LinearLayoutManager.VERTICAL
    }

    recyclerViewLayoutManager.spanSizeLookup = (object : SpanSizeLookup() {
        override fun getSpanSize(position: Int): Int {
            return if(position==0) columns else 1
        }
    })

    val recyclerView: RecyclerView = view!!.findViewById(R.id.recycle1)
    recyclerView.apply {
        layoutManager = recyclerViewLayoutManager
        adapter = ItemAdapter(items)
        addItemDecoration(GridSpacingItemDecoration(20))
        setHasFixedSize(true)
    }

这是装饰物品:

class GridSpacingItemDecoration(space: Int) : RecyclerView.ItemDecoration() {
var spacing: Int = space

override fun getItemOffsets(outRect: Rect,view: View,parent: RecyclerView,state: RecyclerView.State) {
    super.getItemOffsets(outRect,view,parent,state)
    val layoutManager = parent.layoutManager as GridLayoutManager?

    val position = parent.getchildAdapterPosition(view) // item position

        val spanCount: Int
        val column: Int
        // Check the last item and is alone. Then set the parent's width
        if (position == parent.adapter!!.itemCount - 1 && position % 2 == 0) {
            spanCount = 1
            outRect.left = spacing
            outRect.right = parent.width - spacing
        } else {
            spanCount = layoutManager!!.spanCount
            column = position % spanCount
            outRect.left = spacing * (spanCount - column) / spanCount
            outRect.right = spacing * (column + 1) / spanCount
        }
        if (position < spanCount) {
            outRect.top = spacing
        }
        outRect.bottom = spacing

}

}

sarah928 回答:使用不同的权重和大小无法正确绘制加权网格布局

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2792104.html

大家都在问