48.Android 标签TextView的点击技巧
前言
在一些圈子性质的页面里,每条动态的文本往往都是富文本。
其中就有一种掺杂了标签的富文本内容。如新浪微博的标签富文本。
……
……
而且,最重要的是:这些标签可以点击。
这涉及到ClickableSpan的使用。
ClickableSpan源码
/**
* If an object of this type is attached to the text of a TextView
* with a movement method of LinkMovementMethod, the affected spans of
* text can be selected. If clicked, the {@link #onClick} method will
* be called.
*/
public abstract class ClickableSpan extends CharacterStyle implements UpdateAppearance {
/**
* Performs the click action associated with this span.
*/
public abstract void onClick(View widget);
/**
* Makes the text underlined and in the link color.
*/
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ds.linkColor);
ds.setUnderlineText(true);
}
}
ClickableSpan源码很短,主要是拓展了CharacterStyle的updateDrawState功能,和对外提供了一个onClick方法。
我们可以看到ClickableSpan字体的颜色跟随着linkColor的颜色,默认是有下划线的。
但是新浪微博的那个标签是没有下划线的,颜色也最好是可以自定义的。
以上得出:需要自定义一个ClickableSpan。
自定义ClickableSpan
public class ClickableSpanNoUnderline extends ClickableSpan {
private static final String TAG = "ClickableSpan";
private static final int NO_COLOR = -206;
private int color;
private OnClickListener onClickListener;
public ClickableSpanNoUnderline(int color, OnClickListener onClickListener) {
super();
this.color = color;