Skip to content Skip to sidebar Skip to footer

Is It Possible To Set The Color Of A String Directly In String.xml?

I mean something like: Error!

Solution 1:

As suggested by rekire not possible to set color the way you are doing.

You can use the method as suggested by rekire.

In you xml you can specify color for your textview as

  android:textColor="#0EFFFF"

You can also set text color programaticaly

  TextView tv= (TextView)findviewById(R.id.textView1);
  tv.setTextColor(Color.RED);  

To set color of particular words in textview, you can use spannable string

TextView tv= (TextView)findviewById(R.id.textView1);
    tv.setText("");  
    String s="Hello World";
    SpannableString ss=  newSpannableString(s);                
    ss.setSpan(newForegroundColorSpan(Color.GREEN), 0, 5, 0);  
    tv.setText(ss);

Solution 2:

Prior to 4.x, you could do this:

<stringname="error"><fontfgcolor="#ff9a1d1d">Error!</font></string>

However, bug https://code.google.com/p/android/issues/detail?id=58192 broke this functionality because it introduced an integer parser that can't handle numbers with the highest bit set, and unfortunately you can't omit the opacity part of the color (which most people would prefer to set to ff as in this example.)

I just yesterday learned a clever work-around. What you do is negate the hex color value in two's complement. How you do this depends on your hex calculator, but the easiest way is to subtract your color from 0x100000000. In your case, that would result in 0x100000000 - 0xff9a1d1d = 0x65e2e3. (Or you could just invert it, e.g. 0065e2e2 which would be close enough). You then negate this again with a minus sign:

<stringname="error"><fontfgcolor="-#65e2e3">Error!</font></string>

and voilla! you have your desired color.

Kudos to TWiStErRob for figuring this out in https://stackoverflow.com/a/11577658/338479

ETA: I just discovered that this will crash your app if you do it on a 2.x system; it throws a NumberFormat exception

Solution 3:

Try this one

<stringname="some_text">Font color is <fontfgcolor="#ffff0000">red</font></string>

Solution 4:

Put this code in the string.xml file:

<fontcolor="Red"><ahref="support@legacystories.org">HERE</a></font>

Solution 5:

No this is not possible you have to specify that in your layout. But you can put the color in your colors.xml.

colors.xml

<colorname="foo">#abc123</color>

your_layout.xml

<TextView android:textColor="@color/foo" android:text="@string/error" />

Post a Comment for "Is It Possible To Set The Color Of A String Directly In String.xml?"