Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Linkify:自動辨識電話、網址與 Email

編輯:關於 Android 程式設計

當使用者在 EditText 中輸入電話號碼、網址或 Email 時,我們希望能讓 Android 自動辨識這些內容:點擊電話號碼就撥打電話、點擊網址就開啟瀏覽器。Linkify 正是解決這個問題的利器。

步驟一:佈置 UI

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/tv1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

步驟二:在 MainActivity 中實作

透過 Linkify.addLinks() 並搭配位元旗標,就能指定要辨識哪些類型的內容,讓 TextView 中的對應文字變成可點擊的連結:

public class MainActivity extends Activity {
    private TextView tv;
    private EditText et;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv1);
        et = (EditText) findViewById(R.id.et);
        et.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                tv.setText(et.getText());
                // 判斷輸入的是 URL、EMAIL 還是 PHONE,並自動與系統功能連結
                Linkify.addLinks(tv, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS);
                return false;
            }
        });
    }
}

更簡便的方法:autoLink 屬性

如果是在靜態的 TextView 上啟用自動辨識,其實無需寫任何 Java 程式碼,只要在佈局中加上 android:autoLink 屬性即可:

<TextView
    android:id="@+id/tv1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:autoLink="web|phone|email"
/>

無論是用程式碼的 Linkify 動態處理,還是用 autoLink 屬性靜態宣告,都能讓文字中的電話、網址與 Email 搖身一變成為可互動的連結。

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