Get the value of link text when clicked in a textview in android

后端 未结 3 787
你的背包
你的背包 2020-12-14 11:14

I have a TextView. I have added custom links like \"@abc\", \"#android\" by matching some regex pattern. The links are dis

3条回答
  •  没有蜡笔的小新
    2020-12-14 11:56

    The solution goes like this -

    Call setLinks() with you textview and the text to be added.

    setLinks(textView, text);
    

    setLinks() function is as -

    void setLinks(TextView tv, String text) {
            String[] linkPatterns = {
                    "([Hh][tT][tT][pP][sS]?:\\/\\/[^ ,'\">\\]\\)]*[^\\. ,'\">\\]\\)])",
                    "#[\\w]+", "@[\\w]+" };
            for (String str : linkPatterns) {
                Pattern pattern = Pattern.compile(str);
                Matcher matcher = pattern.matcher(tv.getText());
                while (matcher.find()) {
                    int x = matcher.start();
                    int y = matcher.end();
                    final android.text.SpannableString f = new android.text.SpannableString(
                            tv.getText());
                    InternalURLSpan span = new InternalURLSpan();
                    span.text = text.substring(x, y);
                    f.setSpan(span, x, y,
                            android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tv.setText(f);
                    // tv.setOnLongClickListener(span.l);
    
                }
            }
            tv.setLinkTextColor(Color.BLUE);
            tv.setLinksClickable(true);
            tv.setMovementMethod(LinkMovementMethod.getInstance());
            tv.setFocusable(false);
        }
    

    and the InternalURLSpan class goes like this -

    class InternalURLSpan extends android.text.style.ClickableSpan {
            public String text;
    
            @Override
            public void onClick(View widget) {
                handleLinkClicked(text);
            }
    
        }
    

    handleLinkClicked() is as -

    public void handleLinkClicked(String value) {
        if (value.startsWith("http")) {     // handle http links
        } else if (value.startsWith("@")) { // handle @links
        } else if (value.startsWith("#")) { // handle #links
        }
    }
    

提交回复
热议问题