0

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.

ZGski
  • 2,398
  • 1
  • 21
  • 34

4 Answers4

0

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.

Community
  • 1
  • 1
RominaV
  • 3,335
  • 1
  • 29
  • 59
0

you could use a model object for it. E.g.

 public class MyColor {
    public String mColorName;
    public int mColor;

    public MyColor (String name, int color) {
       mColorName = name;
       mColor = color;
    }
 }

and then declare your array like

 MyColor[] color = new MyColor[] { new MyColor("yellow", Color.YELLOW),  new MyColor("white", Color.WHITE), new MyColor("green", Color.GREEN) };

This way you can easily access the name associated to the color

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
0

With this way you have one array and easier to manage.

public class MyColor {
    public String name;
    public int code;

    public MyColor(String n, int c) {
        this.name = n;
        this.code = c;
    }

}

ArrayList<MyColor> colors = new ArrayList<>();
colors.add(new MyColor("black", Color.BLACK));
colors.add(new MyColor("yellow", Color.YELLOW));
colors.add(new MyColor("green", Color.GREEN));

for (MyColor color : colors) {
    if(color.name.equals(colorStr)) {
        yourTextView.setTextColor(color.name);
    }
}
Ozgur
  • 3,738
  • 17
  • 34
0

Try this code:

if(tv.getTextColors().getDefaultColor() == colors[0])
    tv.setText(words[0]);
else if(tv.getTextColors().getDefaultColor() == colors[1])
    tv.setText(words[1]);
else if(tv.getTextColors().getDefaultColor() == colors[2])
    tv.setText(words[2]);
Mahmoud Ibrahim
  • 1,057
  • 11
  • 20