
Common 前言
- TextView 自動判斷是否有 Email、電話或者網址
- 若使用網址,於 AndroidManifest.xml增加連接網路的權限:
 <uses-permission android:name="android.permission.INTENT"/>
方法1:Layout 前端
說明
Example 範例
<TextView          
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:autoLink="web"
    android:gravity="center"
    android:text="@string/test" />
方法2:Java class 後端
說明
- setAutoLinkMask():設定 autoLink 種類,其常數屬於 Linkify 類別- 
- WEB_URLS
- EMAIL_ADDRESSES
- PHONE_NUMBERS
- MAP_ADDRESSES
- ALL
 
- 於 Java class 加入
- setAutoLinkMask()
- setMovementMethod()
 
Example 範例
<TextView          
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="@string/test" />
TextView textView = (TextView) findViewById(R.id.test);
textView.setAutoLinkMask(Linkify.WEB_URLS);
textView.setMovementMethod(LinkMovementMethod.getInstance());
方法3:改用 <a> tag,不使用 autoLink
說明
- 將網址字串改為:<a href='https://www.google.com.tw/'>google</a>
- 於 Java class 加入
Example 範例
<?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="test"><a href='https://www.google.com.tw/'>google</a></string>
    </resources>
<TextView          
    android:id="@+id/test"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="@string/test" />
TextView textView = (TextView) findViewById(R.id.test);
textView.setMovementMethod(LinkMovementMethod.getInstance());
Extensive Reading 延伸閱讀
- Geocoding API
 https://developers.google.com/maps/documentation/geocoding/intro?hl=zh-tw
- TextView autoLink小技巧 - 从源码的角度理解并解决autoLink的所有大坑
 https://www.jianshu.com/p/d3bef8449960
Reference 參考資料
- Linkify 官方文件
 https://developer.android.com/reference/android/text/util/Linkify
- MovementMethod 官方文件
 https://developer.android.com/reference/android/text/method/MovementMethod
- 在Android實作HTML TextView與AutoLink使用的建議方式
 https://magiclen.org/android-html-textview/
 
 
沒有留言:
張貼留言