1

I want to change the color of many textView at once programatically. Ideally instead of referencing each textView individually I would like to alter for example a color in colors.xml (with each textView having this color). Here is some code to help illustrate:

luminance = (0.2126f * RGBRed) + (0.7152f * RGBGreen) + (0.0722f * RGBBlue);

    if(luminance >= 160) {
        //change color of multiple textViews to black
    } else {
        //change color of multiple textViews to white
    }

Is there an easy way to do this or do I have to reference each textView?

mtmeyer
  • 300
  • 1
  • 4
  • 13

2 Answers2

1

You can use styles.

If you reference the style like this in your layouts:

<TextView
style="@style/MyTextViewStyle"
android:text="@string/hello" />

and add a styles.xml in the res/values/ folder with this content:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyTextViewStyle" parent="@android:style/TextAppearance.Medium">
        <item name="android:textColor">#0000FF</item>
    </style>
</resources>

you only need to update the color at one place: in the styles.xml file.

EDIT - ah, you mean changing it at runtime. Then I'd suggest to take a look at this answer.

Community
  • 1
  • 1
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
  • Can I change the styles in java? I have a slider and when it goes below a certain point i want the multiple textViews to change colour from black to white. – mtmeyer Aug 08 '15 at 10:49
  • Sorry, that wasn't clear from your original question. You should still use styles and switch them dynamically as described [here](http://stackoverflow.com/a/6390025/4751173). – Glorfindel Aug 08 '15 at 10:56
-1

I suggest you to use SpannableString

you can set custom color to each part of your textview here is an example:

TextView myTV = (TextView)findViewById(R.id.textView1); String textString = "this is a test text for you"; Spannable spanText = Spannable.Factory.getInstance().newSpannable(textString); spanText.setSpan(new BackgroundColorSpan(0xFFFFFF00), 4, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); myTV.setText(spanText);

Hamid Reza
  • 624
  • 7
  • 23