user6397494 user6397494 - 4 months ago 29x
Android Question

setTextColor depending on random String from array - Android

I have a String array with color names and an array with colors:

String[] words = new String[] {"yellow", "white", "green"};
int[] colors = new int[] {Color.YELLOW, Color.WHITE, Color.GREEN};

is set to one of these words randomly and now I want to set the text color to yellow if yellow was chosen, etc. I tried this with an
statement, but it keeps showing only black words.


1) Retrieve the word that the TextView has:

String chosenWord = String.valueOf(yourTextView.getText());

2) Get the chosenWord position in words:

int position = Arrays.asList(words).indexOf(chosenWord);

3) Get the corresponding color:

int newColor = Color.BLACK;
if(position > -1) {
    newColor = colors[position];

For all the ways to change a TextView color check this.

BTW, do you know Map? You can use them in this cases when you need to map a key with an specific value.