Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

讓 TextView 自動辨識超連結

編輯:進階開發

要在 TextView 裡讓網址、電子郵件與電話號碼變成可點擊的連結,其實不必自己寫解析。只要設定了 android:autoLink,Android 就會自動把符合規則的文字包成可點的 Span。

一、字串資源

先把要顯示的文字放進 strings.xml。內容刻意混雜了網址、信箱與電話,用來觀察 autoLink 的辨識範圍。

<resources>
    <string name="autolink_text">
This is autolink text example.
If you click on link https://www.google.com, then it will launch web browser.
If you click on wzyang@gmail.com, then it will launch email program.
And, if you click on phone number (626)888-6666,
it should dial the phone automatically.
    </string>
</resources>

二、版面配置

關鍵就是 autoLink 屬性與 textSize 的設定。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:autoLink="all"
        android:textSize="25sp"
        android:text="@string/autolink_text" />
</LinearLayout>

autoLink="all" 表示網址、電子郵件、電話與地圖座標全都要辨識。若只想開放部分類型,可以改成 web、email、phone 或 map,多種類型則用「|」串接,例如 autoLink="web|email"。全開雖然方便,但在文字裡出現數字時容易被誤判為電話號碼,實際專案裡建議只開需要的類型。

另外要注意,autoLink 只在 View 建立時作用一次。若文字是執行期動態更新的,改完 setText 之後連結不會自動重算,得改用 Linkify.addLinks(textView, Linkify.ALL) 重新處理;或者直接在字串裡用 HTML 標籤(透過 Html.fromHtml)標明連結,這樣控管上更精準。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved