乐者为王

Do one thing, and do it well.

Android下显示本地Contact Number信息

首先要在AndroidManifest.xml中设置允许读取联系人的权限:

1
<uses-permission android:name="android.permission.READ_CONTACTS" />

联系人列表布局文件contact_list.xml:

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
    <ListView android:id="@+id/contactList"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

联系人列表项布局文件contact_entry.xml:

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
    <TextView android:id="@+id/contactName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView android:id="@+id/contactNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity.java文件内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_list);

        ListView contactList = (ListView)findViewById(R.id.contactList);

        Cursor contactsCursor = managedQuery(People.CONTENT_URI,
                null, null, null, null);
        startManagingCursor(contactsCursor);

        String[] columnsToMap = new String[] {People.NAME, People.NUMBER};
        int[] mapTo = new int[] {R.id.contactName, R.id.contactNumber};

        SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
                R.layout.contact_entry, contactsCursor,
                columnsToMap, mapTo);
        contactList.setAdapter(mAdapter);
    }
}

Comments