android—Text中電話號碼、網址自動連結

來源:互聯網
上載者:User

假若TextView文本中有電話號碼或者網址,我想通過點擊電話號碼或者網址就能實現打電話或者開啟網頁,android中已經為我們提供這樣的屬性和方法進行設定,大體可以分為三種:

1、設定TextView的autoLink屬性:他有幾個值all、web、phone、email等。當文中有這幾種類型的文本值時,點擊它將進入網頁、打電話或者email的activity,這是最簡單的方法

2、在文本值直接添加連結

    (1)例如在string.xml檔案中:<string><a href=http://www.google.com>http://www.google.com</a> <a href="tel:18600000001">tel</a> </string>,同時設定TextView屬性setMovementMethod(LinkMovementMethod.getInstance());

    (2)在代碼中使用Hteml.fromHtml構建文本

代碼

        tv2.setText(
Html.fromHtml("the google url: " +
"<a href=\"http://www.google.com\">http://www.google.com</a><br/>" +
"the telephone: " +
"<a href=\"tel:18603045201\">18603045201</a>)"
));
tv2.setMovementMethod(LinkMovementMethod.getInstance());

3、使用SpanableString指定某段字串為連結文本

 

代碼

        TextView tv3=(TextView)findViewById(R.id.tv3);
SpannableString ss=
new SpannableString("the google url: http://www.google.com 18600000001");
ss.setSpan(new URLSpan("http://www.google.com"),
16, 37, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new URLSpan("tel:18603045201"),
38, 49, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv3.setText(ss);
tv3.setMovementMethod(LinkMovementMethod.getInstance());

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.