android - 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
)
解决方案
经过一番脑筋急转弯并在评论者的帮助下,我发现了这一点:
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 个按钮基本相同
推荐阅读
- angular - Angular Services:Promise 返回奇怪的结果
- cofoundry - 如何使用 Cofoundry 在程序集中嵌入视图文件
- javascript - JavaScript 中无法解释的浮点除法行为
- php - 使用 Simplesamlphp 在 AuthnRequest 中为 Extensions 标签添加命名空间
- r - 如何在 R 中使用 xpath 获得评论
- python - 获取树线输入
- python-3.x - Python在打开文件时出现问题
- mongodb - Mongoose 聚合:无法使用查找填充 2 级嵌套字段
- c++ - 重载解析在模板函数中的工作方式是否不同?
- bash - 需要读取文件并在两个空行之间抓取每个文本块