How to change the colour of text programmatically [duplicate] - android

As the title says, I want to know is it possible to achieve two different colored characters in a single textview element.

yes, if you format the String with html's font-color property then pass it to the method Html.fromHtml(your text here)
String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));

You can prints lines with multiple colors without HTML as:
TextView textView = (TextView) findViewById(R.id.mytextview01);
Spannable word = new SpannableString("Your message");
word.setSpan(new ForegroundColorSpan(Color.BLUE), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(word);
Spannable wordTwo = new SpannableString("Your new message");
wordTwo.setSpan(new ForegroundColorSpan(Color.RED), 0, wordTwo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(wordTwo);

I have done this way:
Set Color on Text by passing String and color:
private String getColoredSpanned(String text, String color) {
String input = "<font color=" + color + ">" + text + "</font>";
return input;
}
Set text on TextView / Button / EditText etc by calling below code:
TextView:
TextView txtView = (TextView)findViewById(R.id.txtView);
Get Colored String:
String name = getColoredSpanned("Hiren", "#800000");
String surName = getColoredSpanned("Patel","#000080");
Set Text on TextView of two strings with different colors:
txtView.setText(Html.fromHtml(name+" "+surName));
Done

You can use Spannable to apply effects to your TextView:
Here is my example for colouring just the first part of a TextView text (while allowing you to set the color dynamically rather than hard coding it into a String as with the HTML example!)
mTextView.setText("Red text is here", BufferType.SPANNABLE);
Spannable span = (Spannable) mTextView.getText();
span.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, "Red".length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
In this example you can replace 0xFFFF0000 with a getResources().getColor(R.color.red)

Use SpannableStringBuilder
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);
SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);

I have done this, try it:
TextView textView=(TextView)findViewById(R.id.yourTextView);//init
//here I am appending two string into my textView with two diff colors.
//I have done from fragment so I used here getActivity(),
//If you are trying it from Activity then pass className.this or this;
textView.append(TextViewUtils.getColoredString(getString(R.string.preString),ContextCompat.getColor(getActivity(),R.color.firstColor)));
textView.append(TextViewUtils.getColoredString(getString(R.string.postString),ContextCompat.getColor(getActivity(),R.color.secondColor)));
Inside your TextViewUtils class add this method:
/***
*
* #param mString this will setup to your textView
* #param colorId text will fill with this color.
* #return string with color, it will append to textView.
*/
public static Spannable getColoredString(String mString, int colorId) {
Spannable spannable = new SpannableString(mString);
spannable.setSpan(new ForegroundColorSpan(colorId), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Log.d(TAG,spannable.toString());
return spannable;
}

It's better to use the string in the strings file, as such:
<string name="some_text">
<![CDATA[
normal color <font color=\'#06a7eb\'>special color</font>]]>
</string>
Usage:
textView.text=HtmlCompat.fromHtml(getString(R.string.some_text), HtmlCompat.FROM_HTML_MODE_LEGACY)

Kotlin version of #Swapnil Kotwal's answer.
Android Studio 4.0.1, Kotlin 1.3.72
val greenText = SpannableString("This is green,")
greenText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someGreenColor), null), 0, greenText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.text = greenText
val yellowText = SpannableString("this is yellow, ")
yellowText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someYellowColor), null), 0, yellowText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(yellowText)
val redText = SpannableString("and this is red.")
redText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someRedColor), null), 0, redText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(redText)

I don't know, since when this is possible, but you can simply add <font> </font> to your string.xml which will automatically change the color per text. No need to add any additional code such as spannable text etc.
Example
<string name="my_formatted_text">
<font color="#FF0707">THIS IS RED</font>
<font color="#0B132B">AND NOW BLUE</font>
</string>

I have write down some code for other question which is similar to this one, but that question got duplicated so i can't answer there so i am just putting my code here if someone looking for same requirement.
It's not fully working code, you need to make some minor changes to get it worked.
Here is the code:
I've used #Graeme idea of using spannable text.
String colorfulText = "colorfulText";
Spannable span = new SpannableString(colorfulText);
for ( int i = 0, len = colorfulText.length(); i < len; i++ ){
span.setSpan(new ForegroundColorSpan(getRandomColor()), i, i+1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
((TextView)findViewById(R.id.txtSplashscreenCopywrite)).setText(span);
Random Color Method:
private int getRandomColor(){
Random rnd = new Random();
return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}

Using Kotlin and Extensions you can add colored text really easy and clean:
Create a file TextViewExtensions.kt with this content
fun TextView.append(string: String?, #ColorRes color: Int) {
if (string == null || string.isEmpty()) {
return
}
val spannable: Spannable = SpannableString(string)
spannable.setSpan(
ForegroundColorSpan(ContextCompat.getColor(context, color)),
0,
spannable.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
append(spannable)
}
Now is really easy to append text with color
textView.text = "" // Remove old text
textView.append("Red Text", R.color.colorAccent)
textView.append("White Text", android.R.color.white)
Basically is same as #Abdul Rizwan answer but using Kotlin, extensions, some validations and getting color inside extension.

Kotlin Answer
fun setTextColor(tv:TextView, startPosition:Int, endPosition:Int, color:Int){
val spannableStr = SpannableString(tv.text)
val underlineSpan = UnderlineSpan()
spannableStr.setSpan(
underlineSpan,
startPosition,
endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
val backgroundColorSpan = ForegroundColorSpan(this.resources.getColor(R.color.agreement_color))
spannableStr.setSpan(
backgroundColorSpan,
startPosition,
endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
val styleSpanItalic = StyleSpan(Typeface.BOLD)
spannableStr.setSpan(
styleSpanItalic,
startPosition,
endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
tv.text = spannableStr
}
After, call above function. You can call more than one:
setTextColor(textView, 0, 61, R.color.agreement_color)
setTextColor(textView, 65, 75, R.color.colorPrimary)
Output:
You can see underline and different colors with each other.

Try this:
mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" + "<br />" +
"<small>" + description + "</small>" + "<br />" +
"<small>" + DateAdded + "</small>"));

Use SpannableBuilder class instead of HTML formatting where it possible because it more faster then HTML format parsing.
See my own benchmark "SpannableBuilder vs HTML" on Github
Thanks!

If you want to give text color and text size in strings.xml then check out the below code:
<string name="txt_my_string">
<font fgcolor='#CFD8DC' > Text with given color </font> // Custom text color
<font size="14" > Text with given size </font> // Custom Text size
<font fgcolor='#3A55EA' size="14" > Text with given color and size </font> // Custom text color and size
</string>
Hope you understand easily :)

Awesome answers! I was able to use Spannable to build rainbow colored text (so this could be repeated for any array of colors). Here's my method, if it helps anyone:
private Spannable buildRainbowText(String pack_name) {
int[] colors = new int[]{Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE};
Spannable word = new SpannableString(pack_name);
for(int i = 0; i < word.length(); i++) {
word.setSpan(new ForegroundColorSpan(colors[i]), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return word;
}
And then I just setText(buildRainboxText(pack_name));
Note that all of the words I pass in are under 15 characters and this just repeats 5 colors 3 times - you'd want to adjust the colors/length of the array for your usage!

if (Build.VERSION.SDK_INT >= 24) {
Html.fromHtml(String, flag) // for 24 API and more
} else {
Html.fromHtml(String) // or for older API
}
for 24 API and more (flag)
public static final int FROM_HTML_MODE_COMPACT = 63;
public static final int FROM_HTML_MODE_LEGACY = 0;
public static final int FROM_HTML_OPTION_USE_CSS_COLORS = 256;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_BLOCKQUOTE = 32;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_DIV = 16;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_HEADING = 2;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST = 8;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM = 4;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH = 1;
public static final int TO_HTML_PARAGRAPH_LINES_CONSECUTIVE = 0;
public static final int TO_HTML_PARAGRAPH_LINES_INDIVIDUAL = 1;
More Info

Since API 24 you have FROM_HTML_OPTION_USE_CSS_COLORS so you can define colors in CSS instead of repeating it all time with font color="
Much clearer - when you have some html and you want to highlight some predefined tags - you just need to add CSS fragment at top of your html

Make common funtion for convert your string spannable like this.
//pass param textviewid ,start,end,string
//R.color.Red it's your color you can change it as requirement
fun SpannableStringWithColor(view: TextView,start:Int,end:Int, s: String) {
val wordtoSpan: Spannable =
SpannableString(s)
wordtoSpan.setSpan(
ForegroundColorSpan(ContextCompat.getColor(view.context, R.color.Red)),
start,
end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
view.text = wordtoSpan
}
We can use anywhere as requirement like this.
SpannableStringWithColor(tvMobileNo,0,14,"Mobile Number : " + "123456789")
SpannableStringWithColor(tvEmail,0,5,"Email : " + "abc#gmail.com" "))
SpannableStringWithColor(tvAddress,0,8,"Address : " + "Delhi India")

Builder function in Kotlin:
val text = buildSpannedString {
append("My red text")
setSpan(
ForegroundColorSpan(ContextCompat.getColor(requireContext(), R.color.red)),
3,
6,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
textView?.setText(text)

for kotlin:
#JvmStatic
#BindingAdapter(
"app:txt1",
"app:txt2",
"app:color1",
"app:color2",
requireAll = false
)
fun setColors(
txtView: AppCompatTextView,
txt1: String,
txt2: String,
color1: Int,
color2: Int
) {
txtView.setColors(txt1 = txt1, txt2 = txt2, color1 = color1, color2)
}
fun AppCompatTextView.setColors(txt1: String, txt2: String, color1: Int, color2: Int) {
val word: Spannable = SpannableString(txt1)
word.setSpan(
ForegroundColorSpan(ContextCompat.getColor(this.context, color1)),
0,
word.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
this.text = word
val wordTwo: Spannable = SpannableString(txt2)
wordTwo.setSpan(
ForegroundColorSpan(ContextCompat.getColor(this.context, color2)),
0,
wordTwo.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
this.append(wordTwo)
}
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:txt1="#{}"
app:txt2="#{}"
app:color1="#{}"
app:color2="#{}" />

Related

set background for only a part of TextView

For example, I have a textview (multi line): aaaaaaaaabbbbaaa. I want to set background for only 'bbb' characters. I try to use Spannable but it doesn't work with my background is a image from drawable.
Many thanks.
using BackgroundColorSpan you can do that ,but Chinese doesn`t work in right way .
private void replaceText(TextView text, String str, int color) {
Spannable raw = new SpannableString(text.getText());
BackgroundColorSpan[] spans = raw.getSpans(0,raw.length(),BackgroundColorSpan.class);
for (BackgroundColorSpan span : spans) {
raw.removeSpan(span);
}
int index = TextUtils.indexOf(raw, str);
while (index >= 0) {
raw.setSpan(new BackgroundColorSpan(color), index, index + str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
index = TextUtils.indexOf(raw, str, index + str.length());
}
text.setText(raw);
}
private fun highlightTextPart(
textView: TextView,
mainString: String,
subString: String
) {
if (mainString.contains(subString)) {
val startIndex = mainString.indexOf(subString)
val endIndex = startIndex + subString.length
val spannableString = SpannableString(mainString)
spannableString.setSpan(
BackgroundColorSpan(Color.parseColor("#ff00ff")),
startIndex,
endIndex,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
textView.text = spannableString
}
}
using
highlightTextPart("text text sell text", textView, "sell");

How to clear formatting from an EditText?

I have an EditText, and can add formatting such as bold, italic....but how can I remove it? I've looked into getSpans, filters, and other non-string things and haven't been able to make sense of them! Ideally, I'd like to be able to clear specific tags and all tags set around the selected text.
Update with my solution:
private String getSelectedText(){
int start = Math.max(mText.getSelectionStart(), 0);
int end = Math.max(mText.getSelectionEnd(), 0);
return mText.getText().toString().substring(Math.min(start, end), Math.max(start, end));
}
private void clearFormat(){
int s1 = Math.max(mText.getSelectionStart(), 0);
int s2 = Math.max(mText.getSelectionEnd(), 0);
String text = getSelectedText(); if(text==""){ return; }
EditText prose = mText;
Spannable raw = new SpannableString(prose.getText());
CharacterStyle[] spans = raw.getSpans(s1, s2, CharacterStyle.class);
for (CharacterStyle span : spans) {
raw.removeSpan(span);
}
prose.setText(raw);
//Re-select
mText.setSelection(Math.min(s1,s2), Math.max(s1, s2));
}
but how can I remove it?
Call removeSpan() on the Spannable.
For example, this method from this sample project searches for a search string in the contents of a TextView and assigns it a background color, but only after removing any previous background colors:
private void searchFor(String text) {
TextView prose=(TextView)findViewById(R.id.prose);
Spannable raw=new SpannableString(prose.getText());
BackgroundColorSpan[] spans=raw.getSpans(0,
raw.length(),
BackgroundColorSpan.class);
for (BackgroundColorSpan span : spans) {
raw.removeSpan(span);
}
int index=TextUtils.indexOf(raw, text);
while (index >= 0) {
raw.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
+ text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
index=TextUtils.indexOf(raw, text, index + text.length());
}
prose.setText(raw);
}
}
what you could try is:
1- Create a custom style where your EditText will have "such as bold, italic..."
2- Be aware of using R.style.normalText to change it back to it's normal style at runtime
3- Change this styles depending on the behaviour you want to achieve via setTextAppearance(Context context, int resid)
Here is an example i found googling How to change a TextView's style at runtime
Edit: as your question is "How to clear formatting from an EditText" here is the specific answer as code:
editTextToClearStyle.setTextAppearance(this,R.style.normalText);
Please see the comment of the snippet below.
if (makeItalic) {
SpannableString spanString = new SpannableString(textViewDescription.getText());
spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
this.textViewDescription.setText(spanString);
} else {
SpannableString spanString = new SpannableString(
textViewDescription.getText().toString()); // NOTE: call 'toString()' here!
spanString.setSpan(new StyleSpan(Typeface.NORMAL), 0, spanString.length(), 0);
this.textViewDescription.setText(spanString);
}
... just get the raw string characters by calling the toString() method.

Seeking the Simplest way to have a TextView's text colored in diffrent colors

I want to have some of the string that is shown by a text view to be red, and some black, how can i do that?
is there a way to mention it simply on the XML file? (strings.xml)
I think you can use span. Text Style
For Example,
final SpannableStringBuilder sb = new SpannableStringBuilder(" text must be here ");
final ForegroundColorSpan fc1 = new ForegroundColorSpan(Color.rgb(255, 0, 0));
final ForegroundColorSpan fc2 = new ForegroundColorSpan(Color.rgb(255, 255, 255));
sb.setSpan(fc1 , 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
sb.setSpan(fc2, 5, 8, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
yourTextView.setText(sb);
(or)
In styles XML, declare the color values as shown below
<color name="redColor">#ff0000</color>
and use it in the layout xml, for the textColor attribute,
android:textColor="#color/redColor"
you can try this,
String.replaceAll(textToHighlight,<font color="red">textToHighlight</font>);
Textview.setText(Html.fromHtml(String));
I believe the only way of doing it is to use a spanned type as below.
TextView textview = (TextView)findViewById(R.id.myTextview);
String firstName = "FirstName";
String lastName = "LastName";
Spanned details = Html.fromHtml(firstName + "<br />" + "<small><font color=\"#767676\">" + lastName + "</b></small>");
textview.setText(details);
Hope this helps

Single TextView with multiple colored text

As the title says, I want to know is it possible to achieve two different colored characters in a single textview element.
yes, if you format the String with html's font-color property then pass it to the method Html.fromHtml(your text here)
String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));
You can prints lines with multiple colors without HTML as:
TextView textView = (TextView) findViewById(R.id.mytextview01);
Spannable word = new SpannableString("Your message");
word.setSpan(new ForegroundColorSpan(Color.BLUE), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(word);
Spannable wordTwo = new SpannableString("Your new message");
wordTwo.setSpan(new ForegroundColorSpan(Color.RED), 0, wordTwo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(wordTwo);
I have done this way:
Set Color on Text by passing String and color:
private String getColoredSpanned(String text, String color) {
String input = "<font color=" + color + ">" + text + "</font>";
return input;
}
Set text on TextView / Button / EditText etc by calling below code:
TextView:
TextView txtView = (TextView)findViewById(R.id.txtView);
Get Colored String:
String name = getColoredSpanned("Hiren", "#800000");
String surName = getColoredSpanned("Patel","#000080");
Set Text on TextView of two strings with different colors:
txtView.setText(Html.fromHtml(name+" "+surName));
Done
You can use Spannable to apply effects to your TextView:
Here is my example for colouring just the first part of a TextView text (while allowing you to set the color dynamically rather than hard coding it into a String as with the HTML example!)
mTextView.setText("Red text is here", BufferType.SPANNABLE);
Spannable span = (Spannable) mTextView.getText();
span.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, "Red".length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
In this example you can replace 0xFFFF0000 with a getResources().getColor(R.color.red)
Use SpannableStringBuilder
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);
SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);
I have done this, try it:
TextView textView=(TextView)findViewById(R.id.yourTextView);//init
//here I am appending two string into my textView with two diff colors.
//I have done from fragment so I used here getActivity(),
//If you are trying it from Activity then pass className.this or this;
textView.append(TextViewUtils.getColoredString(getString(R.string.preString),ContextCompat.getColor(getActivity(),R.color.firstColor)));
textView.append(TextViewUtils.getColoredString(getString(R.string.postString),ContextCompat.getColor(getActivity(),R.color.secondColor)));
Inside your TextViewUtils class add this method:
/***
*
* #param mString this will setup to your textView
* #param colorId text will fill with this color.
* #return string with color, it will append to textView.
*/
public static Spannable getColoredString(String mString, int colorId) {
Spannable spannable = new SpannableString(mString);
spannable.setSpan(new ForegroundColorSpan(colorId), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Log.d(TAG,spannable.toString());
return spannable;
}
It's better to use the string in the strings file, as such:
<string name="some_text">
<![CDATA[
normal color <font color=\'#06a7eb\'>special color</font>]]>
</string>
Usage:
textView.text=HtmlCompat.fromHtml(getString(R.string.some_text), HtmlCompat.FROM_HTML_MODE_LEGACY)
Kotlin version of #Swapnil Kotwal's answer.
Android Studio 4.0.1, Kotlin 1.3.72
val greenText = SpannableString("This is green,")
greenText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someGreenColor), null), 0, greenText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.text = greenText
val yellowText = SpannableString("this is yellow, ")
yellowText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someYellowColor), null), 0, yellowText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(yellowText)
val redText = SpannableString("and this is red.")
redText.setSpan(ForegroundColorSpan(resources.getColor(R.color.someRedColor), null), 0, redText.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
yourTextView.append(redText)
I don't know, since when this is possible, but you can simply add <font> </font> to your string.xml which will automatically change the color per text. No need to add any additional code such as spannable text etc.
Example
<string name="my_formatted_text">
<font color="#FF0707">THIS IS RED</font>
<font color="#0B132B">AND NOW BLUE</font>
</string>
I have write down some code for other question which is similar to this one, but that question got duplicated so i can't answer there so i am just putting my code here if someone looking for same requirement.
It's not fully working code, you need to make some minor changes to get it worked.
Here is the code:
I've used #Graeme idea of using spannable text.
String colorfulText = "colorfulText";
Spannable span = new SpannableString(colorfulText);
for ( int i = 0, len = colorfulText.length(); i < len; i++ ){
span.setSpan(new ForegroundColorSpan(getRandomColor()), i, i+1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
((TextView)findViewById(R.id.txtSplashscreenCopywrite)).setText(span);
Random Color Method:
private int getRandomColor(){
Random rnd = new Random();
return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}
Using Kotlin and Extensions you can add colored text really easy and clean:
Create a file TextViewExtensions.kt with this content
fun TextView.append(string: String?, #ColorRes color: Int) {
if (string == null || string.isEmpty()) {
return
}
val spannable: Spannable = SpannableString(string)
spannable.setSpan(
ForegroundColorSpan(ContextCompat.getColor(context, color)),
0,
spannable.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
append(spannable)
}
Now is really easy to append text with color
textView.text = "" // Remove old text
textView.append("Red Text", R.color.colorAccent)
textView.append("White Text", android.R.color.white)
Basically is same as #Abdul Rizwan answer but using Kotlin, extensions, some validations and getting color inside extension.
Kotlin Answer
fun setTextColor(tv:TextView, startPosition:Int, endPosition:Int, color:Int){
val spannableStr = SpannableString(tv.text)
val underlineSpan = UnderlineSpan()
spannableStr.setSpan(
underlineSpan,
startPosition,
endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
val backgroundColorSpan = ForegroundColorSpan(this.resources.getColor(R.color.agreement_color))
spannableStr.setSpan(
backgroundColorSpan,
startPosition,
endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
val styleSpanItalic = StyleSpan(Typeface.BOLD)
spannableStr.setSpan(
styleSpanItalic,
startPosition,
endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE
)
tv.text = spannableStr
}
After, call above function. You can call more than one:
setTextColor(textView, 0, 61, R.color.agreement_color)
setTextColor(textView, 65, 75, R.color.colorPrimary)
Output:
You can see underline and different colors with each other.
Try this:
mBox = new TextView(context);
mBox.setText(Html.fromHtml("<b>" + title + "</b>" + "<br />" +
"<small>" + description + "</small>" + "<br />" +
"<small>" + DateAdded + "</small>"));
Use SpannableBuilder class instead of HTML formatting where it possible because it more faster then HTML format parsing.
See my own benchmark "SpannableBuilder vs HTML" on Github
Thanks!
If you want to give text color and text size in strings.xml then check out the below code:
<string name="txt_my_string">
<font fgcolor='#CFD8DC' > Text with given color </font> // Custom text color
<font size="14" > Text with given size </font> // Custom Text size
<font fgcolor='#3A55EA' size="14" > Text with given color and size </font> // Custom text color and size
</string>
Hope you understand easily :)
Awesome answers! I was able to use Spannable to build rainbow colored text (so this could be repeated for any array of colors). Here's my method, if it helps anyone:
private Spannable buildRainbowText(String pack_name) {
int[] colors = new int[]{Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE};
Spannable word = new SpannableString(pack_name);
for(int i = 0; i < word.length(); i++) {
word.setSpan(new ForegroundColorSpan(colors[i]), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return word;
}
And then I just setText(buildRainboxText(pack_name));
Note that all of the words I pass in are under 15 characters and this just repeats 5 colors 3 times - you'd want to adjust the colors/length of the array for your usage!
if (Build.VERSION.SDK_INT >= 24) {
Html.fromHtml(String, flag) // for 24 API and more
} else {
Html.fromHtml(String) // or for older API
}
for 24 API and more (flag)
public static final int FROM_HTML_MODE_COMPACT = 63;
public static final int FROM_HTML_MODE_LEGACY = 0;
public static final int FROM_HTML_OPTION_USE_CSS_COLORS = 256;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_BLOCKQUOTE = 32;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_DIV = 16;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_HEADING = 2;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST = 8;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM = 4;
public static final int FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH = 1;
public static final int TO_HTML_PARAGRAPH_LINES_CONSECUTIVE = 0;
public static final int TO_HTML_PARAGRAPH_LINES_INDIVIDUAL = 1;
More Info
Since API 24 you have FROM_HTML_OPTION_USE_CSS_COLORS so you can define colors in CSS instead of repeating it all time with font color="
Much clearer - when you have some html and you want to highlight some predefined tags - you just need to add CSS fragment at top of your html
Make common funtion for convert your string spannable like this.
//pass param textviewid ,start,end,string
//R.color.Red it's your color you can change it as requirement
fun SpannableStringWithColor(view: TextView,start:Int,end:Int, s: String) {
val wordtoSpan: Spannable =
SpannableString(s)
wordtoSpan.setSpan(
ForegroundColorSpan(ContextCompat.getColor(view.context, R.color.Red)),
start,
end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
view.text = wordtoSpan
}
We can use anywhere as requirement like this.
SpannableStringWithColor(tvMobileNo,0,14,"Mobile Number : " + "123456789")
SpannableStringWithColor(tvEmail,0,5,"Email : " + "abc#gmail.com" "))
SpannableStringWithColor(tvAddress,0,8,"Address : " + "Delhi India")
Builder function in Kotlin:
val text = buildSpannedString {
append("My red text")
setSpan(
ForegroundColorSpan(ContextCompat.getColor(requireContext(), R.color.red)),
3,
6,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
textView?.setText(text)
for kotlin:
#JvmStatic
#BindingAdapter(
"app:txt1",
"app:txt2",
"app:color1",
"app:color2",
requireAll = false
)
fun setColors(
txtView: AppCompatTextView,
txt1: String,
txt2: String,
color1: Int,
color2: Int
) {
txtView.setColors(txt1 = txt1, txt2 = txt2, color1 = color1, color2)
}
fun AppCompatTextView.setColors(txt1: String, txt2: String, color1: Int, color2: Int) {
val word: Spannable = SpannableString(txt1)
word.setSpan(
ForegroundColorSpan(ContextCompat.getColor(this.context, color1)),
0,
word.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
this.text = word
val wordTwo: Spannable = SpannableString(txt2)
wordTwo.setSpan(
ForegroundColorSpan(ContextCompat.getColor(this.context, color2)),
0,
wordTwo.length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
this.append(wordTwo)
}
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:txt1="#{}"
app:txt2="#{}"
app:color1="#{}"
app:color2="#{}" />

Set color of TextView span in Android

Is it possible to set the color of just span of text in a TextView?
I would like to do something similar to the Twitter app, in which a part of the text is blue. See image below:
(source: twimg.com)
Another answer would be very similar, but wouldn't need to set the text of the TextView twice
TextView TV = (TextView)findViewById(R.id.mytextview01);
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TV.setText(wordtoSpan);
Here is a little help function. Great for when you have multiple languages!
private void setColor(TextView view, String fulltext, String subtext, int color) {
view.setText(fulltext, TextView.BufferType.SPANNABLE);
Spannable str = (Spannable) view.getText();
int i = fulltext.indexOf(subtext);
str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
I always find visual examples helpful when trying to understand a new concept.
Background Color
SpannableString spannableString = new SpannableString("Hello World!");
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(backgroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
Foreground Color
SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(foregroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
Combination
SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(foregroundSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(backgroundSpan, 3, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
Further Study
Explain the meaning of Span flags like SPAN_EXCLUSIVE_EXCLUSIVE
Android Spanned, SpannedString, Spannable, SpannableString and CharSequence
If you want more control, you might want to check the TextPaint class. Here is how to use it:
final ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(final View textView) {
//Your onClick code here
}
#Override
public void updateDrawState(final TextPaint textPaint) {
textPaint.setColor(yourContext.getResources().getColor(R.color.orange));
textPaint.setUnderlineText(true);
}
};
Set your TextView´s text spannable and define a ForegroundColorSpan for your text.
TextView textView = (TextView)findViewById(R.id.mytextview01);
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(wordtoSpan);
Another way that could be used in some situations is to set the link color in the properties of the view that is taking the Spannable.
If your Spannable is going to be used in a TextView, for example, you can set the link color in the XML like this:
<TextView
android:id="#+id/myTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorLink="#color/your_color"
</TextView>
You can also set it in the code with:
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setLinkTextColor(your_color);
Here's a Kotlin Extension Function I have for this
fun TextView.setColouredSpan(word: String, color: Int) {
val spannableString = SpannableString(text)
val start = text.indexOf(word)
val end = text.indexOf(word) + word.length
try {
spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text = spannableString
} catch (e: IndexOutOfBoundsException) {
println("'$word' was not not found in TextView text")
}
}
Use it after you have set your text to the TextView like so
private val blueberry by lazy { getColor(R.color.blueberry) }
textViewTip.setColouredSpan("Warning", blueberry)
String text = "I don't like Hasina.";
textView.setText(spannableString(text, 8, 14));
private SpannableString spannableString(String text, int start, int end) {
SpannableString spannableString = new SpannableString(text);
ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);
spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
Output:
Set Color on Text by passing String and color:
private String getColoredSpanned(String text, String color) {
String input = "<font color=" + color + ">" + text + "</font>";
return input;
}
Set text on TextView / Button / EditText etc by calling below code:
TextView:
TextView txtView = (TextView)findViewById(R.id.txtView);
Get Colored String:
String name = getColoredSpanned("Hiren", "#800000");
Set Text on TextView:
txtView.setText(Html.fromHtml(name));
Done
There's a factory for creating the Spannable, and avoid the cast, like this:
Spannable span = Spannable.Factory.getInstance().newSpannable("text");
Just to add to the accepted answer, as all the answers seem to talk about android.graphics.Color only: what if the color I want is defined in res/values/colors.xml?
For example, consider Material Design colors defined in colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="md_blue_500">#2196F3</color>
</resources>
(android_material_design_colours.xml is your best friend)
Then use ContextCompat.getColor(getContext(), R.color.md_blue_500) where you would use Color.BLUE, so that:
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
becomes:
wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Where I found that:
Working with spans in Android – Michael Spitsin – Medium
Using kotlin-ktx, you can achieve it easily
bindView?.oneTimePasswordTitle?.text = buildSpannedString {
append("One Time Password ")
inSpans(
ForegroundColorSpan(ContextCompat.getColor(bindView?.oneTimePasswordTitle?.context!!,R.color.colorPrimaryText))
){
append(" (As Registered Email)")
}
}
Some answers here aren't up to date. Because, you will (in most of cases) add a custom clic action on your link.
Besides, as provided by the documentation help, your spanned string link color will have a default one.
"The default link color is the theme's accent color or android:textColorLink if this attribute is defined in the theme".
Here is the way to do it safely.
private class CustomClickableSpan extends ClickableSpan {
private int color = -1;
public CustomClickableSpan(){
super();
if(getContext() != null) {
color = ContextCompat.getColor(getContext(), R.color.colorPrimaryDark);
}
}
#Override
public void updateDrawState(#NonNull TextPaint ds) {
ds.setColor(color != -1 ? color : ds.linkColor);
ds.setUnderlineText(true);
}
#Override
public void onClick(#NonNull View widget) {
}
}
Then to use it.
String text = "my text with action";
hideText= new SpannableString(text);
hideText.setSpan(new CustomClickableSpan(){
#Override
public void onClick(#NonNull View widget) {
// your action here !
}
}, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
yourtextview.setText(hideText);
// don't forget this ! or this will not work !
yourtextview.setMovementMethod(LinkMovementMethod.getInstance());
Hope this will strongly help !
create textview in ur layout
paste this code in ur MainActivity
TextView textview=(TextView)findViewById(R.id.textviewid);
Spannable spannable=new SpannableString("Hello my name is sunil");
spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textview.setText(spannable);
//Note:- the 0,5 is the size of colour which u want to give the strring
//0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily
Below works perfectly for me
tvPrivacyPolicy = (TextView) findViewById(R.id.tvPrivacyPolicy);
String originalText = (String)tvPrivacyPolicy.getText();
int startPosition = 15;
int endPosition = 31;
SpannableString spannableStr = new SpannableString(originalText);
UnderlineSpan underlineSpan = new UnderlineSpan();
spannableStr.setSpan(underlineSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
ForegroundColorSpan backgroundColorSpan = new ForegroundColorSpan(Color.BLUE);
spannableStr.setSpan(backgroundColorSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
StyleSpan styleSpanItalic = new StyleSpan(Typeface.BOLD);
spannableStr.setSpan(styleSpanItalic, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tvPrivacyPolicy.setText(spannableStr);
Output for above code
From the developer docs, to change the color and size of a spannable:
1- create a class:
class RelativeSizeColorSpan(size: Float,#ColorInt private val color: Int): RelativeSizeSpan(size) {
override fun updateDrawState(textPaint: TextPaint?) {
super.updateDrawState(textPaint)
textPaint?.color = color
}
}
2 Create your spannable using that class:
val spannable = SpannableStringBuilder(titleNames)
spannable.setSpan(
RelativeSizeColorSpan(1.5f, Color.CYAN), // Increase size by 50%
titleNames.length - microbe.name.length, // start
titleNames.length, // end
Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)
You can use extension function in Kotlin
fun CharSequence.colorizeText(
textPartToColorize: CharSequence,
#ColorInt color: Int
): CharSequence = SpannableString(this).apply {
val startIndexOfText = this.indexOf(textPartToColorize.toString())
setSpan(ForegroundColorSpan(color), startIndexOfText, startIndexOfText.plus(textPartToColorize.length), 0)
}
Usage:
val colorizedText = "this text will be colorized"
val myTextToColorize = "some text, $colorizedText continue normal text".colorizeText(colorizedText,ContextCompat.getColor(context, R.color.someColor))
viewBinding.myTextView.text = myTextToColorize
Now you can use the CodeView library to highlight patterns with different colors easily, for example, to highlight all URLs inside the text with the blue color you just need to write
CodeView codeView = findViewById(R.id.codeview);
codeView.addSyntaxPattern(Patterns.WEB_URL, Color.BLUE);
codeView.setTextHighlighted(text);
CodeView Repository URL: https://github.com/amrdeveloper/codeview
I got the same issue.
#Dano's answer is absolutely correct. But it doesn't work for me.
After that, I found the issue I have added ClickableSpan. So it will change my color with another color (accent color)
Issue
SpannableStringBuilder will not change color and undline when you add a ClickableSpan after ForegroundColorSpan or UnderlineSpan.
Solution
1. With ClickableSpan
You can Override the updateDrawState method inside ClickableSpan.
In the updateDrawState method, you should remove the super callback.
After that, you should Modify your text paint as required.
2. Without ClickableSpan
Add ForegroundColorSpan to change the text color
Add UnderlineSpan to add underline in text.
First Part **Second Part should be Bold** last Part
This text should be changed using SpannableString
import android.graphics.Typeface.BOLD
import android.text.Spannable
import android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
import android.text.SpannableString
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
val firstPart = "First Part "
val secondPart = "Second Part should be Bold"
val thirdPart = " last Part"
val finalString = firstPart + secondPart + thirdPart
val sb: Spannable = SpannableString(finalString).also {
// ... Change text Colour
it.setSpan(
ForegroundColorSpan(getColor(requireContext(), R.color.pink)),
finalString.indexOf(secondPart),
finalString.indexOf(secondPart) + secondPart.length,
SPAN_EXCLUSIVE_EXCLUSIVE
)
// ... Make the text Bold
it.setSpan(
StyleSpan(BOLD),
finalString.indexOf(secondPart),
finalString.indexOf(secondPart) + secondPart.length,
SPAN_EXCLUSIVE_EXCLUSIVE
)
// ... Change Background Colour
it.setSpan(
BackgroundColorSpan(getColor(requireContext(), R.color.lightPink)),
finalString.indexOf(secondPart) - 1,
finalString.indexOf(secondPart) + secondPart.length + 1,
SPAN_EXCLUSIVE_EXCLUSIVE
)
}
yourTextView.text = sb

Categories

Resources