2 different colors for Text in same text view in android [duplicate]
Asked Answered
M

5

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

Method answered 27/2, 2013 at 12:4 Comment(1)
Have You tried developer.android.com/reference/android/text/Spannable.html or #6279941?Rintoul
L
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));
Lysippus answered 27/2, 2013 at 12:10 Comment(5)
Oh, didnt see the other one, anyways thank you.Method
then mark as answered ;)Lysippus
This does not work anymore (tested on 4.2.2 device)Hanover
this should be marked as accepted answerDannie
Here is an update : The color value should not contains Alpha channel !Sabayon
J
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));
Jigaboo answered 27/2, 2013 at 12:11 Comment(0)
P
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));
Pemberton answered 27/2, 2013 at 12:10 Comment(0)
K
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);
Kimono answered 27/2, 2013 at 12:18 Comment(0)
B
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);
Billmyre answered 27/2, 2013 at 12:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.