3

使用 TextView 显示电子邮件,并设置


TextView tvEmail = (TextView)this.findViewById(R.id.tvEmail);
Linkify.addLinks(tvEmail, Linkify.EMAIL_ADDRESSES);

点击上面的邮件地址会引发异常,因为邮件客户端没有找到。如何赶上这个异常?

4

1 回答 1

2

我已经遇到了同样的问题,我通过创建一个新类来解决它,该类null在实际启动Intent.

您所要做的就是URLSpan在设置 ' 文本之前替换所有跨度TextView(这意味着您不能使用setAutoLinkMask())。

必须这样做,因为URLSpan'sonClick()方法不执行任何类型的null检查。

如何进行:

TextView txt = ...
txt.setLinksClickable(true);
txt.setText(SafeURLSpan.parseSafeHtml(<<YOUR STRING GOES HERE>>));
txt.setMovementMethod(LinkMovementMethod.getInstance());

可用于的字符串种类<<YOUR STRING GOES HERE>>

"Click here: <a href=\"http://google.com\">My links</a>"
"Mail me: <a href=\"mailto:john@doe.com\">My email</a>"
... and so on...

这是SafeURLSPan类的源代码(我在我的应用FPlay中使用它,并且已经在 Android 10+ 上进行了测试):

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Browser;
import android.text.Html;
import android.text.Spannable;
import android.text.style.URLSpan;
import android.view.View;

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

    @Override
    public void onClick(View widget) {
        try {
            final Uri uri = Uri.parse(getURL());
            final Context context = widget.getContext();
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (context != null && intent != null) {
                intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
                context.startActivity(intent);
            }
        } catch (Throwable ex) {
        }
    }

    public static CharSequence parseSafeHtml(CharSequence html) {
        return replaceURLSpans(Html.fromHtml(html.toString()));
    }

    public static CharSequence replaceURLSpans(CharSequence text) {
        if (text instanceof Spannable) {
            final Spannable s = (Spannable)text;
            final URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
            if (spans != null && spans.length > 0) {
                for (int i = spans.length - 1; i >= 0; i--) {
                    final URLSpan span = spans[i];
                    final int start = s.getSpanStart(span);
                    final int end = s.getSpanEnd(span);
                    final int flags = s.getSpanFlags(span);
                    s.removeSpan(span);
                    s.setSpan(new SafeURLSpan(span.getURL()), start, end, flags);
                }
            }
        }
        return text;
    }
}
于 2014-09-25T15:14:48.763 回答