安卓:TextView的超级链接超级链接、TextView

2023-09-12 02:56:54 作者:托尼·屎塔坨

我知道,如果你把一个链接在一个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);
        }
}

然后在你的主Activity类,你有TextViews这个方法添加

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);
 
精彩推荐
图片推荐