編輯:開發入門
在輸入框裡打字時,如果輸入的是電話號碼,點下去就能直接撥號;如果是網址,點下去就開啟瀏覽器;如果是 Email,就跳出郵件程式。這種「文字自動變成可點擊連結」的效果,在 Android 中靠 Linkify 就能輕鬆做到。
新增一個 Android 專案,命名為 LinkifyDemo。
打開 main.xml,放入一個提示文字、一個輸入框與一個用來顯示結果的 TextView:
<?XML version="1.0" encoding="utf-8"?>
<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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="請輸入電話或者 E-mail 或者網址:"
/>
<EditText
android:id="@+id/et1"
android:layout_width="340px"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
package com.android.test;
import android.app.Activity;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class LinkifyDemo extends Activity {
private EditText et;
private TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 取得控制項
et = (EditText)findViewById(R.id.et1);
tv = (TextView)findViewById(R.id.tv1);
// 掛上事件回應
et.setOnKeyListener(new EditText.OnKeyListener(){
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
tv.setText(et.getText());
// 判斷輸入的類型屬於哪一種,並與系統建立連結
Linkify.addLinks(tv, Linkify.WEB_URLS
| Linkify.EMAIL_ADDRESSES | Linkify.PHONE_NUMBERS);
return false;
}
});
}
}
關鍵就在 Linkify.addLinks():第一個參數是要處理的 TextView,第二個參數用位元 OR 組合成「要辨識的類型」。這裡同時打開了網址、Email 與電話號碼三種樣式,因此不論輸入哪一種,Linkify 都會自動把符合規則的字串包成可點擊的連結,點擊後由系統分派給對應的應用程式處理。
以輸入電話為例,當我們點擊畫面上的號碼時,系統會自動調用撥號程式:



其實還有更省事的做法。如果你只是要讓某個 TextView 自動辨識連結,不必寫 Java 程式,直接在版面配置中宣告 autoLink 屬性即可:
<TextView
android:id="@+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="web|phone|email"
/>
autoLink 支援 web、email、phone、map 與 all 等值,效果與 Linkify.addLinks() 相同。兩者的差別在於彈性:autoLink 是宣告式的,適合靜態內容;Linkify 則能在程式執行階段動態決定要處理的 TextView 與比對規則,還可以搭配自訂的 Pattern 與 MatchFilter 做更客製化的辨識。
用 Eclipse 與 Android 元件做開發(四):用 ListView 與 ContentProvider 做通訊錄
用 ListView 元件:一個簡單的範例應用 這一節我們要動手做一個範例應用,用 ListView 元件把電話簿裡的所有聯絡人列出來(見圖 9a、9b)。這個例子不只示
對 Android 開發者有益的 40 條優化建議
Android 開發不只是把功能做出來,還需要考慮相容性、效能、記憶體、測試與使用者體驗。以下整理 40 條實用建議,適合初學者與中階開發者參考。 先尋找與需求相似的
Android數據庫事務淺析
在Android應用開發中,數據庫操作時常出現,而數據庫事務的處理對應用的穩定性與效率提升至關重要。 首先,Android的數據庫操作——尤其是寫操作——非常慢,把所有操
Android XML 菜單:menu、group 與 item 的配置方式
在 XML 中定義菜單 Android 的菜單可以透過程式建立,也可以放在 XML 資源中。使用 XML 的好處是結構清楚、易於維護,也能把界面設計與程式邏輯分離。 me