Android ClickableSpan 获取文本 onClick() [英] Android ClickableSpan get text onClick()

查看:22
本文介绍了Android ClickableSpan 获取文本 onClick()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 TextView 中的 ClickableSpan,并且我正在尝试获取单击范围的文本.这是我的代码.

I'm working on ClickableSpan in a TextView, and I'm trying to get the clicked span's text. This is my code.

// this is the text we'll be operating on
SpannableString text = new SpannableString("Lorem ipsum dolor sit amet");

// make "dolor" (characters 12 to 17) display a toast message when touched
ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(View view) {
        // This will get "Lorem ipsum dolor sit amet", but I just want "dolor"
        String text = ((TextView) view).getText().toString(); 
        Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    }
};

text.setSpan(clickableSpan, 12, 17, 0);

如您所见,我将 clickablespan 设置为 TextView 从字符 12 到 17,我想在 onClick 事件.

As you can see, I set the clickablespan to the TextView from characters 12 to 17, and I want to get these characters in the onClick event.

反正我能做到吗?或者至少我可以将 12, 17 参数传递给 onClick 事件吗?

Is there anyway I can do that? Or at least can I pass the 12, 17 parameter to onClick event?

谢谢!

推荐答案

试试这个:

public class LoremIpsumSpan extends ClickableSpan {
    @Override
    public void onClick(View widget) {
        // TODO add check if widget instanceof TextView
        TextView tv = (TextView) widget;
        // TODO add check if tv.getText() instanceof Spanned
        Spanned s = (Spanned) tv.getText();
        int start = s.getSpanStart(this);
        int end = s.getSpanEnd(this);
        Log.d(TAG, "onClick [" + s.subSequence(start, end) + "]");
    }
}

这篇关于Android ClickableSpan 获取文本 onClick()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆