Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

讀取聯絡人並顯示在 ListView 中

編輯:Android 開發實例

要把手機裡的聯絡人抓出來放進列表,核心只有三件事:查詢 ContentProvider、用 SimpleCursorAdapter 綁定資料、處理點擊事件。以下是一個可直接參考並稍作修改的完整寫法。

動態建立版面配置

這個範例刻意不用 XML,全部在程式碼中組出介面,方便示範每個物件的職責:

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setBackgroundColor(Color.BLACK);

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.FILL_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT);

listView = new ListView(this);
listView.setBackgroundColor(Color.BLACK);
linearLayout.addView(listView, param);

this.setContentView(linearLayout);

實務上當然還是建議把版面寫進 XML,這裡只是為了讓程式碼自成一體。

查詢聯絡人並綁定到 ListView

// 從資料庫取出聯絡人姓名與號碼
Cursor cur = this.getContentResolver().query(
        People.CONTENT_URI, null, null, null, null);

adapter = new SimpleCursorAdapter(
        this,
        android.R.layout.simple_list_item_2,
        cur,
        new String[] { People.NAME, People.NUMBER },
        new int[] { android.R.id.text1, android.R.id.text2 });

this.startManagingCursor(cur);
listView.setAdapter(adapter);

SimpleCursorAdapter 的建構參數依序是:Context、項目版面、Cursor、資料欄位名稱陣列 from、對應控制項 ID 陣列 to。這裡直接用了系統內建的 simple_list_item_2,它自帶兩個文字行,剛好對應姓名與號碼。

startManagingCursor() 是個貼心設計:它會讓 Activity 自動在生命週期階段管理這個 Cursor,例如在必要時重新查詢、在銷毀時關閉,避免游標洩漏。

處理點擊:取得號碼並撥號

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        // getItemAtPosition 回傳 Object,需向下轉型為 CursorWrapper
        CursorWrapper wrapper = (CursorWrapper) listView.getItemAtPosition(position);

        // 取得欄位索引;若欄名不存在會回傳 -1
        int columnIndex = wrapper.getColumnIndex(People.NUMBER);

        if (!wrapper.isNull(columnIndex)) {
            String number = wrapper.getString(columnIndex);
            Log.d(TAG, "number=" + number);

            // 驗證號碼格式後再撥號
            if (PhoneNumberUtils.isGlobalPhoneNumber(number)) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel://" + number));
                startActivity(intent);
            }
        }
    }
});

幾個關鍵觀念

  • 向下轉型:getItemAtPosition() 的回傳型別是 Object,實際上是 CursorWrapper,必須轉型才能操作。
  • 先檢查 null:getColumnIndex() 找不到欄名時回傳 -1,isNull() 則用來確認該筆資料是否真的填了號碼,兩者都該檢查。
  • 用 ACTION_DIAL 而非直接撥號:ACTION_DIAL 只會帶使用者到撥號頁面並填入號碼,由使用者自己按下通話鍵。若要用 ACTION_CALL 直接撥出,必須先取得 CALL_PHONE 權限。

最後別忘了在 AndroidManifest.xml 加上讀取聯絡人的權限,否則 query() 會因權限不足而失敗。

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