如何确定是否在TextView中触摸了链接或纯文本

时间:2018-09-06 15:26:49

标签: android textview

我有一个TextView,它可能包含可点击的链接。我想在TextView中添加一个点击侦听器,但是当单击链接时,我仍然希望Linkify能够正常处理它。

1 个答案:

答案 0 :(得分:1)

花了我一段时间才能弄清楚这一点,我想分享答案,因为它运行良好,请尽情享受吧!

此代码通过在空格字符“”处分隔字符来遍历字符串。

然后检查每个“单词”是否存在链接。

TextView textView = new TextView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {

            final String text = getText().toString();
            final SpannableString spannableString = new SpannableString(text);
            Linkify.addLinks(spannableString, Linkify.ALL);
            final URLSpan[] spans = spannableString.getSpans(0, text.length(), URLSpan.class);

            final int indexOfCharClicked = getOffsetForPosition(event.getX(), event.getY()) + 1; //Change 0-index to 1-index

            final String [] words = text.split(" ");

            int numCharsTraversed = 0;

            //Find the word that was clicked and check if it's a link
            for (String word : words) {
                if (numCharsTraversed + word.length() < indexOfCharClicked) {
                    numCharsTraversed += word.length() + 1; // + 1 for the space
                } else {
                    for (URLSpan span : spans) {
                        if (span.getURL().contains(word) || word.contains(span.getURL())) {
                            //If the clicked word is a link, calling super will invoke the appropriate action
                            return super.onTouchEvent(event);
                        }
                    }
                    break;
                }
            }

            //If we're here, it means regular text was clicked, not a link
            doSomeAction();
            return true;
        }

    };