Implementation of textview local color change function in Android

When I was working on a project, I encountered a line of text with two colors. When you are a rookie, you will directly think of using multiple textviews to implement it. Later, I learned more and found a simpler method.

Direct code:

Method 1:

XML code snippet:

Java code snippet:

The renderings are as follows:

Of course, you can also change the size of text in two colors.

Java code snippet:

The renderings are as follows:

OK, that's it. A small function is completed.

Method 2:

It is implemented with spannablestring.

Java code snippet:

Among them, "default color red color" is the text you want to change. The setspan method has four parameters. Foregroundcolorspan sets the foreground color for the text, that is, the text color. If you want to add a background color to the text, replace it with backgroundcolorspan. 4 is the starting position of text color change,

Spannablestring. Length() is the end position of the text color change. The last parameter is Boolean, and the following four parameters can be passed in.

Spanned.SPAN_ INCLUSIVE_ Exclusive from the start subscript to the end subscript, including the start subscript

Spanned.SPAN_ INCLUSIVE_ Inclusive starts from the start subscript to the end subscript and includes both the start subscript and the end subscript

Spanned.SPAN_ EXCLUSIVE_ Exclusive starts from the start subscript to the end subscript, but does not include the start subscript and the end subscript

Spanned.SPAN_ EXCLUSIVE_ Inclusive from the start subscript to the end subscript, including the end subscript

The above is all about the implementation of textview local color change function in Android. For more content, you can search the articles you need in programming tips. Thank you for your support.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>