美文网首页
Android 打开TextView中的超链接

Android 打开TextView中的超链接

作者: 苏坡坡要吃婆婆酥 | 来源:发表于2019-08-15 14:05 被阅读0次
textView.setMovementMethod(WebLinkMethod.getInstance(mContext, title));    //代码
android:autoLink="all"  // XML

public class WebLinkMethod extends LinkMovementMethod {

private static WebLinkMethod instance;
private Context context;
private String title;

private WebLinkMethod(Context context) {
    this.context = context;
}

private WebLinkMethod(Context context, String title) {
    this.context = context;
    this.title = title;
}

public static MovementMethod getInstance(Context context) {
    if (instance == null)
        instance = new WebLinkMethod(context);
    return instance;
}

public static MovementMethod getInstance(Context context, String title) {
    if (instance == null)
        instance = new WebLinkMethod(context, title);
    return instance;
}

@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);
        URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
        if (link.length != 0) {
            if (action == MotionEvent.ACTION_UP) {
//                  link[0].onClick(widget);
                Intent intent = new Intent(context, WebActivity.class);
                intent.putExtra("url", link[0].getURL());
                intent.putExtra("title", title);
                context.startActivity(intent);
            } else if (action == MotionEvent.ACTION_DOWN) {
                Selection.setSelection(buffer,
                        buffer.getSpanStart(link[0]),
                        buffer.getSpanEnd(link[0]));
            }
            return true;
        } else {
            Selection.removeSelection(buffer);
        }
    }
    return super.onTouchEvent(widget, buffer, event);
}
}

相关文章

网友评论

      本文标题:Android 打开TextView中的超链接

      本文链接:https://www.haomeiwen.com/subject/ygkzjctx.html