简述
在Android开发中,有时候需要对TextView中文字进行特殊化处理,例如给局部文字设置超链接、颜色、字体,背景色等。Android为我们提供了SpannableString来设置富文本,可以通过给SpannableString设置不同的span来改变TextView中文本的显示效果。
例如
设置ImageSpan来进行图文混排
设置BackgroundColorSpan来改变背景颜色
设置ForegroundColorSpan来改变文字颜色
由于直接设置BackgroundColorSpan背景是直角的,这里讲下如何实现自定义圆角背景,顺便讲下ReplacementSpan这个可高度自定义的span。
首先看下自定义圆角背景的效果
这里的自定义圆角的span其实是继承自ReplacementSpan,看下ReplacementSpan的代码
高度可定制化的Span:ReplacementSpan
public abstract class ReplacementSpan extends MetricAffectingSpan {
/**
* Returns the width of the span. Extending classes can set the height of the span by updating
* attributes of {@link android.graphics.Paint.FontMetricsInt}. If the span covers the whole
* text, and the height is not set,
* {@link #draw(Canvas, CharSequence, int, int, float, int, int, int, Paint)} will not be
* called for the span.
*
* @param paint Paint instance.
* @param text Current text.
* @param start Start character index for span.
* @param end End character index for span.