Textview in Android implements segmented display of strings of different colors

About textview

Textview is one of the most common controls in Android development. There are many attributes recorded in the API, but in the actual development, it also meets many interesting requirements, which is worth trying. Therefore, recording it can not only provide reference for you, but also facilitate searching when you need it

A small knowledge point in the recent development process is that the content displayed by textview needs to be displayed in different colors in segments, as shown in the following figure

There are generally three implementation methods

Here are three methods

Multiple textvew

Use spannablestring

As everyone who has used it knows, the better thing is that spannablestring can accurately control the style of the first few to several characters in a long string

The above just lists several common usages. For more information, please refer to the following classes in the android.text.style package

I wonder if you can see the limitations of the spannablestring above. Yes, spannablestring has the advantages of fine control and the disadvantages are also here. When we use spannablestring, we must specify the character subscript used in the style. What if our string is not of fixed length?

Using HTML

If the usage scenario is that the string length is not fixed, for example, it needs to be filled with data from the server

If the length of the data returned by the server is not fixed, it will be awkward to use spannablestring. At this time, you can consider using HTML

The HTML format is relatively simple, and the font tag is required. For details, see the following example

The above is how textview displays strings of different styles in segments. I hope it will be useful to you

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

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
分享
二维码
< <上一篇
下一篇>>