安卓:textview 超链接 [英] Android: textview hyperlink
问题描述
我知道如果你在 textview 中放置一个链接它会起作用,但如果我想显示例如:
I know that if you put a link in a textview it will work but if I want to display for example:
谷歌堆栈溢出
而不是整个链接(只是标签)我如何使这些链接可点击?
and not the whole link(just the tag) How do i make those links clickable?
推荐答案
你可以有两个单独的 TextViews,如果需要,你可以在你的布局中相应地对齐它们:
You could have two separate TextViews and you could align them accordingly in your layout if needed:
Text1.setText(
Html.fromHtml(
"<a href="http://www.google.com">google</a> "));
Text1.setMovementMethod(LinkMovementMethod.getInstance());
Text2.setText(
Html.fromHtml(
"<a href="http://www.stackoverflow.com">stackoverflow</a> "));
Text2.setMovementMethod(LinkMovementMethod.getInstance());
然后如果你想去掉链接下划线".创建一个类:
Then if you want to strip the "link underline". Create a class:
public class URLSpanNoUnderline extends URLSpan {
public URLSpanNoUnderline(String url) {
super(url);
}
@Override public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
}
然后将此方法添加到您拥有 TextViews 的主 Activity 类中
Then add this method in your main Activity class where you have the TextViews
private void stripUnderlines(TextView textView) {
Spannable s = new SpannableString(textView.getText());
URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
for (URLSpan span: spans) {
int start = s.getSpanStart(span);
int end = s.getSpanEnd(span);
s.removeSpan(span);
span = new URLSpanNoUnderline(span.getURL());
s.setSpan(span, start, end, 0);
}
textView.setText(s);
}
然后在初始化 TextViews 后调用它(在你的 onCreate 中):
And then just call this after you initialised the TextViews (in your onCreate):
stripUnderlines(Text1);
stripUnderlines(Text2);
这篇关于安卓:textview 超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!