安卓Textview 使用SpannableString 设置 ClickableSpan 出现点击事件无效。
注意以下几点:
1. 要注意 文字要设置在 textview setText之前
2. 设置文字之后再设置 setSpan
3. textView 设置 setMovementMethod(LinkMovementMethod.getInstance())
4. 然后会有点击事件效果 ,但是字体点击时会有一个背景点击的选中效果,默认主题色, 如果不想要的话,设置 setHighlightColor(0)//透明色
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);
SpannableString spannableString = new SpannableString("我是一段话,我是一段话");
spannableString.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
// 指定区域文字的 点击事件
// ......
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(Color.RED);// 字体颜色
ds.setUnderlineText(false); // 是否有下划线
}
}, 2, 5, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
/** 这是源码注释 说的很清楚 可以稍微看看 * 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 selected and clicked, the {@link #onClick} method will * be called. * <p> * The text with a <code>ClickableSpan</code> attached will be underlined and the link color will be * used as a text color. The default link color is the theme's accent color or * <code>android:textColorLink</code> if this attribute is defined in the theme. * For example, considering that we have a <code>CustomClickableSpan</code> that extends * <code>ClickableSpan</code>, it can be used like this: * <pre>{@code SpannableString string = new SpannableString("Text with clickable text"); *string.setSpan(new CustomClickableSpan(), 10, 19, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);}</pre> * <img src="{@docRoot}reference/android/images/text/style/clickablespan.png" /> * <figcaption>Text with <code>ClickableSpan</code>.</figcaption> */大概意思:
如果使用LinkMovementMethod的移动方法将此类型的对象附加到TextView的文本,则可以选择受影响的文本范围。如果选中并单击,将调用{@link onClick}方法。
带有<code> ClickableSpan <code>的文本将带有下划线,并且链接颜色将用作文本颜色。默认链接颜色是主题的强调色;如果在主题中定义了此属性,则默认为<code> android:textColorLink <code>。例如,假设我们有一个扩展了<code> ClickableSpan <code>的<code> CustomClickableSpan <code>,则可以这样使用:<pre> {@ code SpannableString string = new SpannableString(“带有 可点击文本的文本” );字符串。 figcaption>