URLSpan

示例1:

URLSpan urlSpan = new URLSpan("http://www.baidu.com");

String text = "打开百度";
SpannableString spannableString = new SpannableString(text);
spannableString.setSpan(urlSpan, 2, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

TextView textView = (TextView) findViewById(R.id.text_view);
//设置超链接为可点击状态
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(spannableString);

示例2:

Parcel parcel = Parcel.obtain();
parcel.writeString("http://www.baidu.com");
parcel.setDataPosition(0);
URLSpan urlSpan = new URLSpan(parcel);

String text = "打开百度";
SpannableString spannableString = new SpannableString(text);
spannableString.setSpan(urlSpan, 2, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

TextView textView = (TextView) findViewById(R.id.text_view);
//设置超链接为可点击状态
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(spannableString);

示例3:

重写onClick(View view)方法,实现超链接被点击的事件处理:

URLSpan urlSpan = new URLSpan("http://www.baidu.com") {
    @Override
    public void onClick(View view) {
        super.onClick(view);
        Toast.makeText(MainActivity.this, getURL(), Toast.LENGTH_LONG).show();
    }
};

String text = "打开百度";
SpannableString spannableString = new SpannableString(text);
spannableString.setSpan(urlSpan, 2, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

TextView textView = (TextView) findViewById(R.id.text_view);
//设置超链接为可点击状态
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(spannableString);

示例4:

重写updateDrawState(TextPaint textPaint)方法,修改超链接的样式、文本颜色:

URLSpan urlSpan = new URLSpan("http://www.baidu.com") {
    @Override
    public void updateDrawState(TextPaint textPaint) {
        textPaint.setColor(Color.argb(255, 54, 92, 124));
        textPaint.setUnderlineText(true);
    }
};

String text = "打开百度";
SpannableString spannableString = new SpannableString(text);
spannableString.setSpan(urlSpan, 2, text.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);

TextView textView = (TextView) findViewById(R.id.text_view);
//设置超链接为可点击状态
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(spannableString);