編輯: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,這裡只是為了讓程式碼自成一體。
// 從資料庫取出聯絡人姓名與號碼
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);
}
}
}
});
最後別忘了在 AndroidManifest.xml 加上讀取聯絡人的權限,否則 query() 會因權限不足而失敗。
Android JSON 解析教學:用 JSONObject 讀懂天氣 API 回傳的資料
JSON(JavaScript Object Notation,JavaScript 物件符號法)是一種以純文字為基礎、與程式語言無關的資料交換格式。因為結構輕量、可讀性
Android 調試工具 DDMS 使用詳解
DDMS 全稱 Dalvik Debug Monitor Service,是 Android 開發中最基礎的一套診斷工具。官方文檔見 developer.android.
Android 網絡連接處理:URL 連接、HttpClient 與 WebView 三種方案
Android 提供多種網絡編程方式,本文逐一說明各自的適用場景與關鍵設定。 方案一:URL + URLConnection/HttpURLConnection jav
ExpandableListView 實作三層樹形菜單的兩個關鍵難題
Android 上做樹形菜單,標準武器是 ExpandableListView,也有人自己繼承 ListView 或 LinearLayout 硬刻。但 Expandab