6

I have a TextView widget, as shown below

<TextView 
        android:text="@string/inputText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

The inputText is defined in Strings.xml as

<String name="inputText">The value of input is positive now</String>

Now, I want the whole text to be displayed in Brown color, and only 'positive' in green color.

Is there any way to do so ? in brief my question is multiple coloring for same textview at the same time

  • Have You tried http://developer.android.com/reference/android/text/Spannable.html or http://stackoverflow.com/questions/6279441/can-textview-have-letters-in-different-colors?rq=1? – sandrstar Feb 27 '13 at 12:06

5 Answers5

15

this is a dublicate of this question Change text color of one word in a TextView.

String first = "This word is ";
String next = "<font color='#EE0000'>red</font>";
t.setText(Html.fromHtml(first + next));
Community
  • 1
  • 1
M4tchB0X3r
  • 1,531
  • 1
  • 15
  • 28
7

You could use CDATA inside your strings.xml to store your string with some HTML formatting, and Html.fromHTML to have this displayed within your TextView.

strings.xml

<string name="inputText">
    <![CDATA[
      <p>The value of input is <font color='#00ff00'>positive</font> now.</p>
    ]]>
</string>

Java Code

myTextView.setText(Html.fromHtml(getString(R.string.inputText));
Rawkode
  • 21,990
  • 5
  • 38
  • 45
2

Use this approach: formate the String with html

String text = "<font color=#cc0029>Text with Color first</font> <font color=#ffcc00>Text with Color second</font>";
yourtextview.setText(Html.fromHtml(text));
Shiv
  • 4,569
  • 4
  • 25
  • 39
1

Use Spannable to do that:

String text = "<font color='brown'>The value of input is </font><font color='green'> positive </font><font color='brown'> color </font>";
textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
KDeogharkar
  • 10,939
  • 7
  • 51
  • 95
0

Try this one,

TextView tv = (TextView)findViewById(R.id.mytextview01);

SpannableString WordtoSpan = tv.getText();

WordtoSpan.setSpan(new ForegroundColorSpan(Color.GREEN), 23, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tv.setText(WordtoSpan);
Ajit
  • 957
  • 1
  • 8
  • 24