編輯:關於 Android 開發
要做一個類似系統通訊錄的頁面,需要解決三件事:讀取聯絡人資料、依姓名首字母分組並讓組標題懸浮固定、點擊項目直接撥號。以下用 PinnedSectionListView 一次搞定。
先用 ContentResolver 查詢 ContactsContract,把結果放進自訂的 Contacts 清單;接著從 A 到 Z 逐字母比對每個聯絡人的首字母,把 GROUP 標題與 CHILD 資料交錯排進同一個資料源;最後由 Adapter 依 viewType 決定哪些項目需要被釘住。
package com.lixu.tongxunlu;
import java.util.ArrayList;
import com.lixu.tongxunlu.PinnedSectionListView.PinnedSectionListAdapter;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends Activity {
private ArrayList<Contacts> contacts;
private ArrayList<Data> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
toggleFullscreen(true);
data = new ArrayList<Data>();
contacts = new ArrayList<Contacts>();
getcontacts(contacts);
int A = (int) 'A';
for (int i = 0; i < 26; i++) {
char c = (char) (A + i);
Data group = new Data();
group.type = Data.GROUP;
group.text = c + "";
data.add(group);
for (int j = 0; j < contacts.size(); j++) {
Contacts cc = contacts.get(j);
// 首字母與組名相同則歸入該組
if (cc.firstLetterofNmae().equals(group.text)) {
Data child = new Data();
child.type = Data.CHILD;
child.text = cc.name + " " + cc.getPhoneNumbers();
child.contacts = cc;
data.add(child);
}
}
}
PinnedSectionListView pslv = (PinnedSectionListView) findViewById(R.id.pslv);
pslv.setAdapter(new MyAdapter(this, -1));
pslv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 只有子項目才會觸發撥號
if (data.get(position).type == Data.CHILD) {
Contacts contact = data.get(position).contacts;
String number = contact.getPhoneNumbers();
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
startActivity(intent);
}
}
});
}
// 全螢幕設定
public void toggleFullscreen(boolean fullScreen) {
WindowManager.LayoutParams attrs = getWindow().getAttributes();
if (fullScreen) {
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
} else {
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
}
getWindow().setAttributes(attrs);
}
private class Data {
public static final int GROUP = 0;
public static final int CHILD = 1;
public static final int STYE = 2;
public String text;
public int type;
public Contacts contacts = null;
}
private class MyAdapter extends ArrayAdapter implements PinnedSectionListAdapter {
private LayoutInflater flater;
public MyAdapter(Context context, int resource) {
super(context, resource);
flater = LayoutInflater.from(context);
}
@Override public int getCount() { return data.size(); }
@Override public Object getItem(int position) { return data.get(position); }
@Override public int getItemViewType(int position) { return data.get(position).type; }
@Override public int getViewTypeCount() { return Data.STYE; }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
Data data = (Data) getItem(position);
switch (type) {
case Data.GROUP:
if (convertView == null)
convertView = flater.inflate(android.R.layout.simple_list_item_1, null);
TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
tv.setBackgroundColor(Color.GREEN);
tv.setTextSize(35);
tv.setText(data.text);
break;
case Data.CHILD:
if (convertView == null)
convertView = flater.inflate(android.R.layout.simple_list_item_1, null);
TextView tv1 = (TextView) convertView.findViewById(android.R.id.text1);
tv1.setTextSize(20);
tv1.setText(data.text);
break;
default:
break;
}
return convertView;
}
// 決定哪些 viewType 需要被釘住
@Override
public boolean isItemViewTypePinned(int viewType) {
switch (viewType) {
case Data.GROUP:
return true;
default:
return false;
}
}
}
// 讀取手機聯絡人
private void getcontacts(ArrayList<Contacts> contacts) {
Uri uri = Uri.parse("content://com.android.contacts/contacts");
ContentResolver resolver = this.getContentResolver();
// 傳入 SORT_KEY_PRIMARY 讓結果依姓名首字母排序
Cursor cursor = resolver.query(uri, null, null, null,
android.provider.ContactsContract.Contacts.SORT_KEY_PRIMARY);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(
android.provider.ContactsContract.Contacts._ID));
String sort_key_primary = cursor.getString(cursor.getColumnIndex(
android.provider.ContactsContract.Contacts.SORT_KEY_PRIMARY));
String name = cursor.getString(cursor.getColumnIndex(
android.provider.ContactsContract.Contacts.DISPLAY_NAME));
Contacts mContacts = new Contacts();
mContacts.id = id;
mContacts.name = name;
mContacts.sort_key_primary = sort_key_primary;
// 同一聯絡人可能有多組號碼
Cursor phone = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null);
ArrayList<String> phonenumbers = new ArrayList<String>();
while (phone.moveToNext()) {
int phoneFieldColumnIndex = phone.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER);
phonenumbers.add(phone.getString(phoneFieldColumnIndex));
}
mContacts.phonenumbers = phonenumbers;
contacts.add(mContacts);
}
}
private class Contacts {
public String id;
public String name;
public String sort_key_primary;
public ArrayList<String> phonenumbers;
// 取排序鍵的第一個字元並轉大寫,作為分組依據
public String firstLetterofNmae() {
String s = sort_key_primary.charAt(0) + "";
return s.toUpperCase();
}
public String getPhoneNumbers() {
String phones = "";
for (int i = 0; i < phonenumbers.size(); i++) {
phones += ":" + phonenumbers.get(i);
}
return phones;
}
}
}
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp" >
<com.lixu.tongxunlu.PinnedSectionListView
android:id="@+id/pslv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
效果示意:

需要在 AndroidManifest.xml 中加入 READ_CONTACTS 與 CALL_PHONE。Android 6.0 以上還必須在執行期動態向使用者請求這兩項權限,否則查詢會直接回傳空結果。
27 個值得借鏡的行動端登入/註冊介面設計靈感
27 個值得借鏡的行動端登入/註冊介面設計靈感 原文來源:Medium,作者 Muzli,譯者 設計達人。 登入/註冊畫面是網站與 App 裡最常見的小元件之一,功能看似
Android 學習指南之二十七:Handler 是怎麼把耗時任務的結果送回主執行緒的
想像一個情境:使用者按下按鈕,而這個按鈕背後要跑一段頗耗時間的運算。如果你直接在 UI 執行緒上硬做,畫面會整個卡住不動,使用者以為 App 當機了。Android 對這
Android 開發中 allowBackup 造成的敏感資訊外洩風險與因應
Android 應用開發:allowBackup 敏感信息洩露的一點反思 1. 背景 這個主題乍聽有點小題大作,但回頭看確實值得一談,有點「陰溝裡翻船」的味道。 And
Android Studio 導入 SlidingMenu 與 FloatMath 找不到符號的解法
Android Studio 導入 SlidingMenu 與 FloatMath 找不到符號的解法 SlidingMenu 是一套廣受歡迎的第三方開源自側滑元件,用互動