且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TextView 可以选择并包含链接吗?

更新时间:2023-11-27 11:39:04

我想通了.您需要继承 LinkMovementMethod 并添加对文本选择的支持.很遗憾它本身不支持它.我只是使用 源代码.我想这是 Android 开源的好处之一!

I figured it out. You need to subclass LinkMovementMethod and add support for text selection. It's really unfortunate that it doesn't support it natively. I just overrode the relevant methods using the equivalent ones from the source code for ArrowKeyMovementMethod. I guess that's one benefit of Android being open source!

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());
       }
    }
}

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

To use it, just instantiate it directly, like so:

textView.setMovementMethod(new CustomMovementMethod());