開發者嘗試通過 LinkMovementMethod 使 TextView 支持鏈接點擊,但發現純文本網址(如 "cnn.com/money" 或 "www.cnn.com/money")無法自動識別為可點擊鏈接。原因是 LinkMovementMethod 僅負責處理已經被識別為 Span 的鏈接,不具備自動識別文本中 URL 的能力。
Android 提供 android.text.util.Linkify 工具類,可自動掃描文本中的 URL、郵箱、電話號碼、地圖地址等模式,並將其轉換為可點擊的 URLSpan。
TextView textView = findViewById(R.id.my_text_view);
// 重置自動鏈接掩碼(可選,避免 XML 中 android:autoLink 干擾)
textView.setAutoLinkMask(0);
// 方案一:識別所有類型(URL、郵箱、電話、地址)
Linkify.addLinks(textView, Linkify.ALL);
// 方案二:僅識別網頁 URL(推薦,精準控制)
Linkify.addLinks(textView, Linkify.WEB_URLS);
若無需動態控制,可直接在布局 XML 中聲明:
<TextView
android:id="@+id/my_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:text="訪問 www.example.com 或 https://google.com" />
對於特定業務格式(如訂單號、邀請碼),可使用 Pattern 定義正則表達式並配合 Linkify.addLinks() 實現自定義鏈接識別:
Pattern orderPattern = Pattern.compile("\\bORD-\\d{8}\\b");
String orderScheme = "myapp://order/";
Linkify.addLinks(textView, orderPattern, orderScheme);
Linkify.WEB_URLS 要求 URL 包含協議頭(https://, https://)或標準域名格式,純 "cnn.com" 可能不被識別,建議數據預處理補全協議。Linkify.addLinks() 後會自動設置 MovementMethod,無需再手動設置 LinkMovementMethod。setOnClickListener 或自定義 URLSpan 攔截點擊事件實現自定義跳轉邏輯。