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

Android 開發:把聯絡人讀進 ListView 並實作點擊撥號

編輯:關於 Android 開發

讀取聯絡人並用 ListView 呈現,是入門 ContentResolver 最經典的練習。以下是一個可直接運行的完整範例。

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class App extends Activity {
    private static final String TAG = "App";
    ListView listView;
    ListAdapter adapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout linearLayout = new LinearLayout(this);// 實例化 linearLayout
        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);// 動態添加 View

        this.setContentView(linearLayout);

        // 從資料庫獲取聯絡人姓名和電話號碼
        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);

        listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
            }
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                // 從指標的封裝類中獲得選中項的電話號碼並撥號
                CursorWrapper wrapper = (CursorWrapper) listView.getItemAtPosition(position);
                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);
                    }
                }
            }
        });
    }
}

程式拆解

1. 用程式碼組版面。這個範例沒有用 XML,而是直接 new 出 LinearLayout 與 ListView 再 addView 掛上去。這樣做的好處是流程集中、容易看懂資料流;缺點是版面一複雜就難維護,實務上還是建議寫在 XML 裡。

2. SimpleCursorAdapter 讓 Cursor 直接變成列表。它的建構子參數依序是 (Context, layout, Cursor, from[], to[]):指定一條 Cursor、告訴它要取哪幾個欄位(from),以及這些欄位要塞進哪個版面配置中的哪些控制項 id(to)。這裡用了系統內建的 simple_list_item_2,它自帶 text1 與 text2 兩個 TextView,剛好對應姓名與號碼。

3. startManagingCursor(cur) 負責生命週期。它會讓 Activity 在必要時自動重新查詢、並在 onDestroy 時關閉 Cursor,避免洩漏。

4. 點擊時向下轉型取欄位。getItemAtPosition() 的回傳值是 Object,需要轉型成 CursorWrapper 才能呼叫 getColumnIndex()。若欄名不存在會回傳 -1,因此後面還要用 isNull() 防一手。

5. 用 ACTION_DIAL 而非 ACTION_CALL。範例刻意使用 Intent.ACTION_DIAL——它只把號碼帶到撥號盤,最後一按仍由使用者決定。若改用 ACTION_CALL 會直接撥出,且必須宣告 CALL_PHONE 權限。無論哪一種,讀取聯絡人都需要 READ_CONTACTS 權限。

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