user6397494 user6397494 - 6 months ago 37
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};


My
TextView
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
if
statement, but it keeps showing only black words.

Answer

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];
}
yourTextView.setTextColor(newColor);

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.

Comments