欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android TextView 超链接显示及跳转

程序员文章站 2022-04-29 17:46:02
...

首先看下效果图

Android TextView 超链接显示及跳转

点击“详情页”进入到我们的App的另一个页面,这是如何实现的呢?先看下代码

textView = findViewById(R.id.text);
SpannableString ss = new SpannableString("具体内容请点击详情页");
ss.setSpan(new CustomURLSpan(""), 7, 10,
         Spanned.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(ss);
textView.setMovementMethod(new CustomMovementMethod(ActionBarActivity.this));//**链接

CustomURLSpan 表示的你自定义字体的样式(有无下划线?字体粗细,颜色等等)

CustomMovementMethod 表示你点击之后的处理操作(点击之后打开网页?跳转到某个App详情页?)

public class CustomURLSpan extends URLSpan {
    public CustomURLSpan(String url) {
        super(url);
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setUnderlineText(false);//无下划线
        ds.setColor(Color.parseColor("#ff0000"));//字体颜色
    }
}
public class CustomMovementMethod extends LinkMovementMethod {
    Context mContext;

    public CustomMovementMethod(Context context) {
        this.mContext = context;
    }

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

        if (action == MotionEvent.ACTION_UP) {

            //长按之后松手是不会跳转到目标页面的,只有短暂点击才会
            if (event.getEventTime() - event.getDownTime() > ViewConfiguration
                    .getLongPressTimeout() - 10) {
                return true;
            }

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

            URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
            if (link.length != 0) {
                String url = link[0].getURL();
                  //点击跳转的逻辑在这里
                Intent intent = new Intent(mContext, MainActivity.class);
                mContext.startActivity(intent);
                return true;
            }
        }
        return super.onTouchEvent(widget, buffer, event);
    }
}

注意下这句话

ss.setSpan(new CustomURLSpan(""), 7, 10,
         Spanned.SPAN_INCLUSIVE_INCLUSIVE);

start 7 end 10 意思是第8个字符(索引为7)到第10个字符