安卓 使用 clickablespan 时点击无效问题

6 篇文章 0 订阅

安卓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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值