views:

57

answers:

2

I want to set the color of the TextView by the function getcolorss. I tried a lot of different ways but i cant get in it. Please help me i think the solution is easy.

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 getcolorss(int x)
{
 switch(x)
 {
 case 1: return Color.BLUE; 
 case 2: return Color.RED;
 } 
}

}

+1  A: 

You can't do it like that since if you call getcolorss(3) there's no return statment. Try either:

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

or

public Color getcolorss(int x)
{
 Color result = null;
 switch(x)
 {
  case 1: result = Color.BLUE; 
  case 2: result = Color.RED;
 }
 // this allows you to do something else here, if you require something more complex
 return result;
}
Andrei Fierbinteanu
+1  A: 

There are many ways to do this. Looking at android.graphics.Color, 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];
polygenelubricants
Thank you thats what i want. But now he marks me "Color.BLUE" and "Color.RED" and give me the error message "Type mismatch: cannot convert from int to Color". Why? Do i need more imports?
Simon Schubert
@Simon: I just checked the documentation and `Color.BLUE` is an `int`, so we need an `int[]` instead. I've fixed the answer to reflect this.
polygenelubricants
Iam an idiot. Thank you it works!
Simon Schubert