Android實現捕獲TextView超連結的方法_Android

來源:互聯網
上載者:User

本文執行個體講述了Android實現捕獲TextView超連結的方法。分享給大家供大家參考,具體如下:

這裡分享一篇捕獲TextView超連結的文章,希望對大家有所協助,我終於在歪路上迴歸正途了。這個捕獲TextView超連結應該算是比較常用吧,如果你會了,就不用看了,如果還不會,可以看一眼,非常簡單。

捕獲TextView超連結這個意思就是在一段文字當中如果有超連結的網址在當中,在TextView中會特別顯示,和其它文字顏色不一樣,還可以點擊執行相應的操作。

效果圖如下:

具體代碼如下:

tv = (TextView) findViewById(R.id.tv); String html = "「非著名程式員」可能是東半球最好的技術分享公眾號。每天,每周定時推送一些有關移動開發的原創文章和教程。 不信你可以\n";html += "<a href='http://www.baidu.com'>百度一下</a> 哈哈,有意思吧!記住微訊號是:smart_android 哦";CharSequence charSequence = Html.fromHtml(html); SpannableStringBuilder builder = new SpannableStringBuilder( charSequence); URLSpan[] urlSpans = builder.getSpans(0, charSequence.length(), URLSpan.class); for (URLSpan span : urlSpans) { int start = builder.getSpanStart(span); int end = builder.getSpanEnd(span); int flag = builder.getSpanFlags(span); final String link = span.getURL(); builder.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { // 捕獲<a>標籤點擊事件,及對應超連結link } }, start, end, flag); builder.removeSpan(span); } tv.setLinksClickable(true); tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setText(charSequence);

其實看完代碼就知道了,非常簡單。大家可以試一試哦

希望本文所述對大家Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.