首页 > 解决方案 > Android GridView 计算背景颜色不均匀

问题描述

在 Kotlin 中为我的 GridView 计算以下问题的一个好的数学方法是什么?

所以在这个gridview中,背景图案是:

[红][蓝][蓝][红][红]等...

现在我已经以编程方式设置了这些颜色,但是如果用户无权看到这个按钮,我很快就会删除一个按钮,然后我的模式就会中断。

我将如何在 Kotlin 的适配器中计算这个?我的代码现在看起来像这样,但我不想摆脱R.color.课堂上的:

    buttons.add(GridViewButton(R.drawable.ic_message, "Account", R.color.buttonRed,this))
    buttons.add(GridViewButton(R.drawable.ic_message, "Account", R.color.buttonBlue,this))
    buttons.add(GridViewButton(R.drawable.ic_message, "Account", R.color.buttonBlue,this))
    buttons.add(GridViewButton(R.drawable.ic_message, "Account", R.color.buttonRed,this))
    buttons.add(GridViewButton(R.drawable.ic_message, "Account", R.color.buttonRed,this))
    buttons.add(GridViewButton(R.drawable.ic_message, "Account", R.color.buttonBlue,this))

class GridViewButton (
    val icon: Int,
    val name: String,
    val color: Int,
    val listener: View.OnClickListener
)

在此处输入图像描述

标签: androidgridviewkotlin

解决方案


经过一番脑筋急转弯并在评论者的帮助下,我发现了这一点:

when (position % 4) {
    0, 3 -> view?.layout_button?.setBackgroundColor(mContext.resources.getColor(R.color.buttonRed))
    1, 2 -> view?.layout_button?.setBackgroundColor(mContext.resources.getColor(R.color.buttonBlue))
}

解释:

总是从position开始0

因此,如果我们为按钮 1 到 4 写下这个。

0 % 4 == 0

1 % 4 == 1

2 % 4 == 2

3 % 4 == 3

我们将第一个和最后一个值设置为红色。第二个和第三个颜色为蓝色。第 5 个按钮与第 1 个按钮基本相同


推荐阅读