在行

时间:2016-10-03 07:56:19

标签: java android

我想改变列表视图的颜色。我想改变像这样的行的颜色。第一种颜色应该是橙色,然后是红色,然后是灰色,然后是绿色。并且这会分别保留它们的位置。

这意味着,对于每一行:

  • position = 0 - >橙
  • position = 1 - >红色
  • position = 2 - >格里
  • position = 3 - >绿色

,这在我的列表视图中重复。

我怎么能这样做?

我知道如何将它更改为奇数或偶数行,但我找不到这个逻辑。

2 个答案:

答案 0 :(得分:1)

您应该检查适配器的getView()方法中的位置。

int result = position % 4;
if(result == 0){
  // set orange background
} else if(result == 1){
  // set red background
} else if(result == 2){
  // set grey background
} else{
  // set green background
}

答案 1 :(得分:0)

您可以使用枚举来匹配值,也可以实现逻辑以返回颜色名称。

有关示例,请参阅下面的代码段。在这里,我的颜色分别基于位置1,2,3和4。

enum Color {
    ORANGE, GREEN, RED, GREY;

    public static String getColorForRow(int position) {
        return Color.values()[position].toString();
    }
}

public class ColorCoder {
    public static void main(String[] args) {
        try {
            System.out.println("Color : " + Color.getColorForRow(5));
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Color doesn't exists.");
        }
    }
}