21

我遇到了一个问题TextView。我可以使用 使其可选择setTextIsSelectable(true),但是当我启用要单击的链接时setMovementMethod(LinkMovementMethod.getInstance()),它不再可选择。

请注意,我的意思不是让原始链接可点击,而是通过TextView使用类似setText(Html.fromHtml("<a href='http://stackoverflow.com'>Hello World!</a>")).

4

8 回答 8

26

奥克斯的回答导致在 textview 上双击时出现异常

java.lang.IndexOutOfBoundsException: setSpan (-1 ... -1) 在 0 之前开始...

我查看了LinkMovementMethod中的onTouchEvent 实现,发现当 textview 不包含链接时它会删除选择。在这种情况下,选择从空值开始,当用户尝试更改它时应用程序崩溃。

...
if (link.length != 0) {
    if (action == MotionEvent.ACTION_UP) {
        link[0].onClick(widget);
    } else if (action == MotionEvent.ACTION_DOWN) {
        Selection.setSelection(buffer,
        buffer.getSpanStart(link[0]),
        buffer.getSpanEnd(link[0]));
    }
  return true;
} else {
  Selection.removeSelection(buffer);
}
...

所以我重写了 onTouchEvent方法,它工作正常。

public class CustomMovementMethod extends LinkMovementMethod {
    @Override
    public boolean canSelectArbitrarily () {
        return true;
    }

    @Override
    public void initialize(TextView widget, Spannable text) {
        Selection.setSelection(text, text.length());
    }

    @Override
    public void onTakeFocus(TextView view, Spannable text, int dir) {
        if ((dir & (View.FOCUS_FORWARD | View.FOCUS_DOWN)) != 0) {
            if (view.getLayout() == null) {
                // This shouldn't be null, but do something sensible if it is.
                Selection.setSelection(text, text.length());
            }
        } else {
            Selection.setSelection(text, text.length());
        }
    }

    @Override
    public boolean onTouchEvent(TextView widget, Spannable buffer,
                                MotionEvent event) {
        int action = event.getAction();

        if (action == MotionEvent.ACTION_UP ||
                action == MotionEvent.ACTION_DOWN) {
            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

            if (link.length != 0) {
                if (action == MotionEvent.ACTION_UP) {
                    link[0].onClick(widget);
                } else if (action == MotionEvent.ACTION_DOWN) {
                    Selection.setSelection(buffer,
                            buffer.getSpanStart(link[0]),
                            buffer.getSpanEnd(link[0]));
                }
                return true;
            }
        }

        return Touch.onTouchEvent(widget, buffer, event);
    }
}

希望它对某人有所帮助。

于 2015-06-01T11:18:46.233 回答
14

我想到了。您需要继承 LinkMovementMethod 并添加对文本选择的支持。很遗憾它本身不支持它。我只是使用源代码中的等效方法覆盖了相关方法ArrowKeyMovementMethod。我想这是 Android 开源的好处之一!

public class CustomMovementMethod extends LinkMovementMethod {
    @Override
    public boolean canSelectArbitrarily () {
        return true;
    }

    @Override
    public void initialize(TextView widget, Spannable text) {
        Selection.setSelection(text, text.length());
    }

    @Override
    public void onTakeFocus(TextView view, Spannable text, int dir) {
       if ((dir & (View.FOCUS_FORWARD | View.FOCUS_DOWN)) != 0) {
           if (view.getLayout() == null) {
               // This shouldn't be null, but do something sensible if it is.
               Selection.setSelection(text, text.length());
           }
       } else {
           Selection.setSelection(text, text.length());
       }
    }
}

要使用它,只需直接实例化它,如下所示:

textView.setMovementMethod(new CustomMovementMethod());
于 2013-04-05T22:00:35.363 回答
4

TL; DR:只需LinkArrowKeyMovementMethod在此答案末尾使用即可获得完美解决方案。

如果您曾经尝试使用扩展的投票最多的答案,则会出现一个烦人的错误LinkMovementMethod——当您通过单击一些未选择的文本来取消选择时,整个选择会从头到尾闪烁,然后变得一无所有。这是因为LinkMovementMethod实际上无法像ArrowKeyMovementMethod.

TextView如果您已设置android:autoLink为,则另一种方法可能是使用自己的解决方法true,如以下来源TextView

        final boolean textIsSelectable = isTextSelectable();
        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;
            }
        }

但是我个人不想要自动链接功能(我有我自己的链接信息),所以在@Weidian Huang 的想法的基础上,我将LinkMovementMethod's 的功能融入ArrowKeyMovementMethod并构建了一个新的移动方法:

/**
 * @see LinkMovementMethod
 * @see ArrowKeyMovementMethod
 */
public class LinkArrowKeyMovementMethod extends ArrowKeyMovementMethod {

    private static final int CLICK = 1;
    private static final int UP = 2;
    private static final int DOWN = 3;

    private static Object FROM_BELOW = new NoCopySpan.Concrete();

    private static LinkArrowKeyMovementMethod sInstance;

    public static LinkArrowKeyMovementMethod getInstance() {
        if (sInstance == null) {
            sInstance = new LinkArrowKeyMovementMethod();
        }
        return sInstance;
    }

    @Override
    public void initialize(TextView widget, Spannable text) {
        super.initialize(widget, text);

        text.removeSpan(FROM_BELOW);
    }

    @Override
    public void onTakeFocus(TextView view, Spannable text, int dir) {
        super.onTakeFocus(view, text, dir);

        if ((dir & View.FOCUS_BACKWARD) != 0) {
            text.setSpan(FROM_BELOW, 0, 0, Spannable.SPAN_POINT_POINT);
        } else {
            text.removeSpan(FROM_BELOW);
        }
    }

    @Override
    protected boolean handleMovementKey(TextView widget, Spannable buffer, int keyCode,
                                        int movementMetaState, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:
            case KeyEvent.KEYCODE_ENTER:
                if (KeyEvent.metaStateHasNoModifiers(movementMetaState)) {
                    if (event.getAction() == KeyEvent.ACTION_DOWN &&
                            event.getRepeatCount() == 0 && action(CLICK, widget, buffer)) {
                        return true;
                    }
                }
                break;
        }
        return super.handleMovementKey(widget, buffer, keyCode, movementMetaState, event);
    }

    @Override
    protected boolean up(TextView widget, Spannable buffer) {
        if (action(UP, widget, buffer)) {
            return true;
        }

        return super.up(widget, buffer);
    }

    @Override
    protected boolean down(TextView widget, Spannable buffer) {
        if (action(DOWN, widget, buffer)) {
            return true;
        }

        return super.down(widget, buffer);
    }

    @Override
    protected boolean left(TextView widget, Spannable buffer) {
        if (action(UP, widget, buffer)) {
            return true;
        }

        return super.left(widget, buffer);
    }

    @Override
    protected boolean right(TextView widget, Spannable buffer) {
        if (action(DOWN, widget, buffer)) {
            return true;
        }

        return super.right(widget, buffer);
    }

    private boolean action(int what, TextView widget, Spannable buffer) {
        Layout layout = widget.getLayout();

        int padding = widget.getTotalPaddingTop() +
                widget.getTotalPaddingBottom();
        int areaTop = widget.getScrollY();
        int areaBot = areaTop + widget.getHeight() - padding;

        int lineTop = layout.getLineForVertical(areaTop);
        int lineBot = layout.getLineForVertical(areaBot);

        int first = layout.getLineStart(lineTop);
        int last = layout.getLineEnd(lineBot);

        ClickableSpan[] candidates = buffer.getSpans(first, last, ClickableSpan.class);

        int a = Selection.getSelectionStart(buffer);
        int b = Selection.getSelectionEnd(buffer);

        int selStart = Math.min(a, b);
        int selEnd = Math.max(a, b);

        if (selStart < 0) {
            if (buffer.getSpanStart(FROM_BELOW) >= 0) {
                selStart = selEnd = buffer.length();
            }
        }

        if (selStart > last)
            selStart = selEnd = Integer.MAX_VALUE;
        if (selEnd < first)
            selStart = selEnd = -1;

        switch (what) {
            case CLICK:
                if (selStart == selEnd) {
                    return false;
                }

                ClickableSpan[] link = buffer.getSpans(selStart, selEnd, ClickableSpan.class);

                if (link.length != 1)
                    return false;

                link[0].onClick(widget);
                break;

            case UP:
                int bestStart, bestEnd;

                bestStart = -1;
                bestEnd = -1;

                for (int i = 0; i < candidates.length; i++) {
                    int end = buffer.getSpanEnd(candidates[i]);

                    if (end < selEnd || selStart == selEnd) {
                        if (end > bestEnd) {
                            bestStart = buffer.getSpanStart(candidates[i]);
                            bestEnd = end;
                        }
                    }
                }

                if (bestStart >= 0) {
                    Selection.setSelection(buffer, bestEnd, bestStart);
                    return true;
                }

                break;

            case DOWN:
                bestStart = Integer.MAX_VALUE;
                bestEnd = Integer.MAX_VALUE;

                for (int i = 0; i < candidates.length; i++) {
                    int start = buffer.getSpanStart(candidates[i]);

                    if (start > selStart || selStart == selEnd) {
                        if (start < bestStart) {
                            bestStart = start;
                            bestEnd = buffer.getSpanEnd(candidates[i]);
                        }
                    }
                }

                if (bestEnd < Integer.MAX_VALUE) {
                    Selection.setSelection(buffer, bestStart, bestEnd);
                    return true;
                }

                break;
        }

        return false;
    }

    @Override
    public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
        int action = event.getAction();

        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
            int x = (int) event.getX();
            int y = (int) event.getY();

            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);
            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] links = buffer.getSpans(off, off, ClickableSpan.class);

            if (links.length != 0) {
                if (action == MotionEvent.ACTION_UP) {
                    links[0].onClick(widget);
                } else if (action == MotionEvent.ACTION_DOWN) {
                    Selection.setSelection(buffer,
                            buffer.getSpanStart(links[0]),
                            buffer.getSpanEnd(links[0]));
                }
                return true;
            }
            // Removed
            //else {
            //    Selection.removeSelection(buffer);
            //}
        }

        return super.onTouchEvent(widget, buffer, event);
    }
}

要使用它,只需调用:

textView.setTextIsSelectable(true);
textView.setMovementMethod(LinkArrowKeyMovementMethod.getInstance());

这对我来说非常有效。

于 2018-06-25T08:16:43.330 回答
2

LinkMovementMethod()不太支持文本选择,即使我们可以选择文本,但是滚动textview之后,选择会丢失。

最好的实现是从 扩展ArrowKeyMovementMethod,它很好地支持文本选择。

请在此处查看详细信息

于 2015-09-19T13:41:15.533 回答
2

XML TextView 不应有任何链接或任何可以选择的属性:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

然后,按照以下顺序以编程方式设置所有内容:

textView.setText(Html.fromHtml(myHtml));
Linkify.addLinks(textView, Linkify.WEB_URLS);
textView.setTextIsSelectable(true); // API-11 and above
textView.setMovementMethod(LinkMovementMethod.getInstance());
于 2017-01-12T07:39:11.967 回答
2

此外,订单很重要

textView.setTextIsSelectable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());

允许内容是可选的,并且链接点击工作完美

于 2018-07-25T06:33:36.173 回答
0

这是我对 Kotlin 的看法(大致基于 @hai-zhang 的回答)。简化!请参阅我的要点以获得更好的版本。我目前将它用于自定义跨度,而不是 HTML,它仍然与我相关,尤其是当我需要将用户点击的位置传递给跨度对象时。

需要在setTextIsSelectable(true)之后设置移动方式

/** Minimal version of Smart Movement that only has limited support of [ClickableSpan] */
object SmartMovementMethodMinimal : ArrowKeyMovementMethod() {

    override fun onTouchEvent(widget: TextView?, buffer: Spannable?, event: MotionEvent?) =
        handleMotion(event!!, widget!!, buffer!!) || super.onTouchEvent(widget, buffer, event)

    private fun handleMotion(event: MotionEvent, widget: TextView, buffer: Spannable): Boolean {
        if (event.action == MotionEvent.ACTION_UP) {
            // Get click position
            val target = Point().apply {
                x = event.x.toInt() - widget.totalPaddingLeft + widget.scrollX
                y = event.y.toInt() - widget.totalPaddingTop + widget.scrollY
            }

            // Get span line and offset
            val line = widget.layout.getLineForVertical(target.y)
            val offset = widget.layout.getOffsetForHorizontal(line, target.x.toFloat())

            if (event.action == MotionEvent.ACTION_UP) {
                val spans = buffer.getSpans<ClickableSpan>(offset, offset)
                if (spans.isNotEmpty()) {
                    spans.forEach { it.onClick(widget) }
                    return true
                }
            }
        }

        return false
    }
}

更详细和复杂的代码与示例在这里:https ://gist.github.com/sQu1rr/210f7e08dd939fa30dcd2209177ba875

于 2020-03-07T23:27:47.597 回答
-1

是否可以将 TextView 与 URL 关联?您是否有 10 个 TextView 和 10 个 URL,编写代码应该很简单,如果单击 TextView[3],它会触发带有 URL[3] 的 webview(或浏览器)的意图

于 2013-04-05T19:26:45.063 回答