preface

Another series for myself

SpannableString can be used to modify specified characters based on character sequences. During daily development, TextView can be modified, such as adding words or sentences, bolding, click events, colors, underscores, and so on to complete text.

SpannableString

The main code

SpannableString().setSpan(what:Object,start:Int,end:Int,flags:Int)
Copy the code

what

This parameter is used to set the Span to be modified

The commonly usedSpan

ForegroundColorSpan

It’s used to set the foreground color, and it’s also used to color the text. The color value needs to be ColorInt, Can use Color. ParseColor (Color: String) or ResourseCompt. GetColor (resoures: Resourse, id: Int, theme: Int) two methods to obtain ColorInt

  • case
val ss = SpannableString("A paragraph.")
ss.setSpan(ForegroundColorSpan(Color.parseColor("# 000000")),2,ss.size(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
textview.setText(ss)
Copy the code

BackgroundColorSpan

As the name implies, used to set the background color, also need to pass the ColorInt, do not do the instance.

ClickableSpan

Click modify. Note: add this Span, the need to be modified textview, setMovementMethod (LinkMovementMehtod. GetInstance ()), otherwise click event will not be issued to the modified paragraphs; ClickableSpan underscores text by default, so if you don’t want underscores you need to setUnderlineText(false) in updateDrawState

  • case
val ss = SpannableString("A paragraph.")

val clickableSpan = object: ClickableSpan(){
	override fun onClick(weiget:View){
		/ / TODO click
	}
	override fun upadteDrawState(paint:TextPaint){
		paint.setUnderlineText(false)
	}
}

ss.setSpan(clickableSpan,2,ss.size(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
textview.setMovementMethod(LinkMovementMehtod.getInstance())
textview.setText(ss)
Copy the code

StyleSpan

Used to set text styles, such as italic and bold. You need to pass in Typeface

Typeface
/ / normal
public static final int NORMAL = 0;
/ / in bold
public static final int BOLD = 1;
/ / italics
public static final int ITALIC = 2;
// Italic + bold
public static final int BOLD_ITALIC = 3;
Copy the code
  • case
val ss = SpannableString("1234")
val bold = StyleSpan(Typeface.BOLD);
ss.setSpan(bold,2,ss.size(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
textview.setText(ss)
Copy the code

In subsequent use, add other Span….

flags

Explain, INCLUSIVE and EXCLUSIVE. INCLUSIVE* is equal to a closed interval, EXCLUSIVE is equal to an open interval, and EXCLUSIVE is equal to an open interval

  • SPAN_INCLUSIVE_EXCLUSIVE: Includes the start index, but not the end index
  • SPAN_EXCLUSIVE_INCLUSIVE: does not include the start subscript, but includes the end subscript
  • SPAN_INCLUSIVE_INCLUSIVE: Includes both start and end subscripts
  • SPAN_EXCLUSIVE_EXCLUSIVE: does not include start or end indices