Android:将 onClickListener 设置为 TextView 中的一部分文本 - 问题 [英] Android: Setting onClickListener to a Part of text in a TextView - Issue

查看:27
本文介绍了Android:将 onClickListener 设置为 TextView 中的一部分文本 - 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试识别 TextView 中的主题标签并使它们可点击,以便在用户点击主题标签时我可以将用户带到另一个视图.

I am trying to recognise hashtags in my TextView and make them clickable such that I can take the user to another View when they click on the Hashtag.

我设法使用模式匹配识别 TextView 中的 Hashtags,它们在运行时显示为彩色.但是,我需要使 Hashtag 可点击.

I managed to identify Hashtags in the TextView using Pattern Matching and they appear colored in Runtime. However, I need to make the Hashtag clickable.

这是我的代码:

 SpannableString hashText = new SpannableString("I just watched #StarWars and it was incredible. It's a #MustWatch #StarWars");
 Matcher matcher = Pattern.compile("#([A-Za-z0-9_-]+)").matcher(hashText);

 while (matcher.find())
 {
          hashText.setSpan(new ForegroundColorSpan(Color.parseColor("#000763")), matcher.start(), matcher.end(), 0);
          String tag = matcher.group(0);
 }

 holder.caption.setText(hashText);

 //I need to set an OnClick listener to all the Hashtags recognised

使用上述相同的解决方案,我如何将 onclick 侦听器添加到每个主题标签?

Using the same solution above, how can I add onclick listeners to every hashtag?

推荐答案

有一种方法......看到你的问题后,我只是在谷歌上搜索......我找到了这个,我希望它会起作用......

there is a way... after seeing your question i was just googling .. and i found this, i hope it will work...

1.你可以使用 android.text.style.ClickableSpan 链接

SpannableString ss = new SpannableString("Hello World");
    ClickableSpan span1 = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            // do some thing
        }
    };

    ClickableSpan span2 = new ClickableSpan() {
        @Override
        public void onClick(View textView) {
            // do another thing
        }
    };

    ss.setSpan(span1, 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(span2, 6, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    textView.setText(ss);
    textView.setMovementMethod(LinkMovementMethod.getInstance());

另一种方式.. 链接

 TextView myTextView = new TextView(this);
    String myString = "Some text [clickable]";
    int i1 = myString.indexOf("[");
    int i2 = myString.indexOf("]");
    myTextView.setMovementMethod(LinkMovementMethod.getInstance());
    myTextView.setText(myString, BufferType.SPANNABLE);
    Spannable mySpannable = (Spannable)myTextView.getText();
    ClickableSpan myClickableSpan = new ClickableSpan()
    {
     @Override
     public void onClick(View widget) { /* do something */ }
    };
    mySpannable.setSpan(myClickableSpan, i1, i2 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

刚刚从这些链接复制的答案...

answer just copied from those link...

这篇关于Android:将 onClickListener 设置为 TextView 中的一部分文本 - 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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