編輯:進階開發
要在 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)標明連結,這樣控管上更精準。
Sidekick 的故事:從 Danger 到 Android(4)明星寵兒與轉折的開始
2004 年秋,明星擁抱新 Sidekick 2003 年的彩色版讓 Sidekick 進入了明星的視野,Paris Hilton 與 Lindsay Lohan 都是使
Android 介面設計入門:布局(Layout)基礎教學
理解布局,是做好 Android 應用設計的關鍵起點。本文提供一份關於布局如何融入 Android 應用架構的概覽,並介紹幾種常用的布局控制元件,說明它們能如何組織應用程
Android 2.4 傳聞 4 月登場 代號並非「冰激凌」
有消息指出,Google 準備在 4 月發布下一個 Android 重要版本,而優派(ViewSonic)將搶先推出搭載 Android 2.4 的裝置。 根據小部落格
圖解 Android 廣播機制(一)
從現實生活中理解廣播 一聽到「廣播」,第一感覺大概會聯想到小時候村裡的大喇叭——每逢村裡有什麼活動,都是透過廣播通知的。收聽收音機也是一種廣播,收音機裡有很多個電台,每個