2012-07-28 30 views
2

使用一個TextView來顯示電子郵件,並設置如何在用戶點擊textview中的鏈接時趕上異常?


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

點擊上面的郵箱地址將引發異常,因爲郵件客戶端沒有找到。如何趕上這個異常?

+0

哪個例外是在textview點擊? – 2012-07-28 07:06:39

+0

@PareshMayani ActivityNotFound,找不到處理Intent的活動{act = android.intent.action.View dat = mailto:xxx} – 2012-07-28 08:00:54

回答

2

我已經有同樣的問題,我通過創建一個新的類,在實際啓動Intent之前檢查null來解決它。

您只需在設置TextView的文本(表示您不能使用setAutoLinkMask())之前替換所有URLSpan跨度即可。

這是必須完成的,因爲URLSpanonClick()方法不會執行任何種類的null檢查。

如何preceed:字符串

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:[email protected]\">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; 
    } 
} 
相關問題