Simon Schubert Simon Schubert - 1 year ago 72
Java Question

Java - Set Color by switch case function

I want to set the color of the TextView by the function getColor(). I tried a lot of different ways but I can't get it working. My code doesn't compile.

import java.awt.*;

public class test extends Activity {

TextView text1 = (TextView) findViewById(;


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


How would you do it?

Answer Source

There are many ways to do this. Looking at, RED, BLUE etc are merely int constants. Therefore, we can have something like this:

int[] pallete = { Color.BLUE, Color.RED };

Then simply:

return pallete[x];

This will naturally throw ArrayIndexOutOfBoundsException when x is out of bounds. You can check for it and do something else if that's what you want. Note that arrays in Java is 0-based, meaning that given the above declaration:

pallete[0] == Color.BLUE
pallete[1] == Color.RED

The original code uses 1-based indexing, so if you need to, you can do simple translation:

return pallete[x-1];