链接和可选择的TextView?

时间:2013-02-13 20:44:19

标签: android textview linkify selectable

我希望TextView可以选择和链接。当我这两样做时,我最终会选择可选文本,但无法点击链接。

编辑:

我将展示代码来解释我的困难:

    TextView textView = view.findViewById(R.id.mytext);
    textView.setText("My text: +4412345678 Go to website: www.google.com Blah blah");
    Linkify.addLinks(textView, Linkify.ALL);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        textView.setTextIsSelectable(true);
    }

3 个答案:

答案 0 :(得分:15)

您是否尝试在TextView xml代码上添加此内容?

    <TextView
    ...
    android:autoLink="all"
    android:textIsSelectable="true" />

我已经在我的代码上试了一下,我可以在网络/邮件上打电话/浏览,也可以选择所有文字。

答案 1 :(得分:14)

autoLink属性有一个令人讨厌的错误:如果您在电话号码中单击您的示例,然后返回并单击第二个网址链接 - 它将再次打开电话号码。这个属性在多个链接上工作得很糟糕,我已经实现了自己的类,这里是Github上的链接ClickableLinksTextView.java

在您的示例中,您可以使用xml-layout中的TextView类替换ClickableLinksTextView类,并更改如下代码:

ClickableLinksTextView textView = (ClickableLinksTextView)view.findViewById(R.id.mytext);
textView.setText("My text: +4412345678 Go to website: www.google.com Blah blah");
Linkify.addLinks(textView, Linkify.ALL);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    textView.setMovementMethod(ArrowKeyMovementMethod.getInstance());
    textView.setTextIsSelectable(true);
    // the autoLink attribute must be removed, if you hasn't set it then ok, otherwise call textView.setAutoLink(0);
}

您问题中问题的原因是LinkMovementMethod类和textIsSelectable属性完全不兼容,即使Android操作系统开发人员也在the Android OS source code承认这一点。

  

不要更改支持文本选择的文本的移动方法,因为它会阻止任意光标位移。

如果文本视图可选,则只有2个正确的移动方法值为nullArrowKeyMovementMethod。这就是我在我的示例中明确设置ArrowKeyMovementMethod的原因,因为Linkify.addLinks设置了错误的移动方法,我应该将其还原。

至于autoLink属性的错误,是因为Android开发人员没有正确复制链接检测。您可以在@cheng yang的答案中查看代码示例,代码只需要第一个链接,无论您拥有多少链接。

答案 2 :(得分:2)

问题出在Android的TextView中。调用Linkify.addLinks()不会更改TextView本身的自动链接掩码。 我认为这是一个Android bug,他们检查了mAutoLinkMask。 因此,如果您在android:autoLink文件中设置xml,或将setAutoLinkMask()调用为非0值,则可以使用。

仅供参考,TextView的源代码:

            if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && textIsSelectable) {
            // The LinkMovementMethod which should handle taps on links has not been installed
            // on non editable text that support text selection.
            // We reproduce its behavior here to open links for these.
            ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(),
                    getSelectionEnd(), ClickableSpan.class);

            if (links.length > 0) {
                links[0].onClick(this);
                handled = true;
            }
        }