如今大部分的App都會有《軟件服務協議》及《隱私協議》,好比手機QQ的註冊頁: html
這樣的需求,在App愈來愈規範化的今天,很是的常見,實現的方式也五花八門,我這裏提供一種簡單方便的,拓展性強的實現方式,先看效果:public SpannableStringBuilder setTextLink(final Context context, String answerstring) {
if(!TextUtils.isEmpty(answerstring)) {
//fromHtml(String source)在Android N中已經棄用,推薦使用fromHtml(String source, int
// flags),flags 參數說明,
// Html.FROM_HTML_MODE_COMPACT:html塊元素之間使用一個換行符分隔
// Html.FROM_HTML_MODE_LEGACY:html塊元素之間使用兩個換行符分隔
Spanned htmlString = Html.fromHtml(answerstring, Html.FROM_HTML_MODE_COMPACT);
if(htmlString instanceof SpannableStringBuilder) {
SpannableStringBuilder spannablestringbuilder =
(SpannableStringBuilder) htmlString;
//取得與a標籤相關的span
Object[] objs = spannablestringbuilder.getSpans(0,
spannablestringbuilder.length(), URLSpan.class);
if(null != objs && objs.length != 0) {
for(Object obj : objs) {
int start = spannablestringbuilder.getSpanStart(obj);
int end = spannablestringbuilder.getSpanEnd(obj);
if(obj instanceof URLSpan) {
//先移除這個span,再新添加一個本身實現的span。
URLSpan span = (URLSpan) obj;
final String url = span.getURL();
spannablestringbuilder.removeSpan(obj);
spannablestringbuilder.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
//這裏能夠實現本身的跳轉邏輯
Toast.makeText(MainActivity.this, url,
Toast.LENGTH_LONG).show();
}
}, start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
}
return spannablestringbuilder;
}
}
return new SpannableStringBuilder(answerstring);
}
複製代碼
String conent = "文本超連接<a href='https://www.google.com/'>Google谷歌</a>及<a " +
"href='https://www.baidu.com/'>Baidu百度</a>";
tvLink.setMovementMethod(LinkMovementMethod.getInstance());//使超連接可點擊
tvLink.setText(setTextLink(this, conent));
複製代碼