Java-按开关盒函数设置颜色

Java-按开关盒函数设置颜色,java,android,colors,Java,Android,Colors,我想通过函数getColor()设置TextView的颜色。我尝试了很多不同的方法,但都没有成功。我的代码无法编译 import java.awt.*; import android.graphics.Color; public class test extends Activity { TextView text1 = (TextView) findViewById(R.id.text1); text1.setTextColor(getcolorss(1)); public Color

我想通过函数getColor()设置TextView的颜色。我尝试了很多不同的方法,但都没有成功。我的代码无法编译

import java.awt.*;
import android.graphics.Color;

public class test extends Activity {

TextView text1 = (TextView) findViewById(R.id.text1);

text1.setTextColor(getcolorss(1));

public Color getColor(int x) {
   switch(x) {
       case 1: return Color.BLUE; 
       case 2: return Color.RED;
   } 
}

}

你会怎么做?

你不能这样做,因为如果你调用getcolorss(3),就没有返回语句。 尝试以下任一方法:

public Color getcolorss(int x)
{
 switch(x)
 {
  case 1: return Color.BLUE; 
  case 2: return Color.RED;
  default: return null;
 } 
}


有很多方法可以做到这一点。看看,
RED
BLUE
等都只是
int
常量。因此,我们可以这样做:

int[] pallete = { Color.BLUE, Color.RED };
然后简单地说:

return pallete[x];
x
超出边界时,这自然会
抛出ArrayIndexOutOfBoundsException
。如果你想要的话,你可以检查一下,然后做些别的事情。请注意,Java中的数组是基于0的,这意味着给定上述声明:

pallete[0] == Color.BLUE
pallete[1] == Color.RED
原始代码使用基于1的索引,因此如果需要,可以执行简单的翻译:

return pallete[x-1];

请包括不起作用的内容,给出的代码似乎无法编译。为什么这不编译是非常不同的,我的文字颜色没有改变,当我运行这个。谢谢你,这就是我想要的。但现在他给我标上了“Color.BLUE”和“Color.RED”,并给了我一条错误消息“Type mismatch:无法从int转换为Color”。为什么?我需要更多的导入吗?@Simon:我刚检查了文档,发现
颜色。蓝色是
int
,所以我们需要
int[]
。我已经确定了答案来反映这一点。
return pallete[x-1];