Android develops methods for changing font colors

  • 2020-06-15 10:12:49
  • OfStack

When adding text in TextView, the color of text font will change. Today, I will share 3 implementation methods and related advantages and disadvantages.

1. Change the text color through html tag


tv.setText(Html.fromHtml(" I am a <font color=blue>danyijiangnan</font>"));

Comment: The Html. fromHtml() method allows you to use the html tag in a string, and the font tag allows you to change the font format. Maizi College - the most professional IT online education platform in China.

2. TextView tv=new TextView(this); Instantiate 1 textview by setContentView(tv); Load it to current activity and set the content to display String str= "Content to display";


SpannableStringBuilder style=new SpannableStringBuilder(str);
//SpannableStringBuilder implementation CharSequence interface
style.setSpan(new ForegroundColorSpan(Color.RED), 0, 2,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
style.setSpan(new ForegroundColorSpan(Color.YELLOW), 2, 4,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
style.setSpan(new ForegroundColorSpan(Color.GREEN), 4, 6,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
tv.setText(style);// Add it to tv In the

Comments: Through the above code can realize part of the text font change, the number in the parameter represents the starting position and the end position, this method is more complex

3. Set the font color directly in the configuration xml file under layout and change the color by adding android: textcolor= "#FFFFFF"

Review: Only 1 color can be displayed in font

This is the end of this article, I hope you enjoy it.


Related articles: