1. 此範例是自動填入文字(AutoCompleteTextView)功能來搜尋電話簿內的聯絡人姓名。

2. 由於我們需取得目前手機的電話簿,因此必需在AndroidManifest.xml內新增一個讀取電話簿的權限。

3. MainActivity.java

01.package org.me.android_phonebook;
02.import android.app.Activity;
03.import android.content.ContentResolver;
04.import android.database.Cursor;
05.import android.os.Bundle;
06.import android.provider.Contacts;
07.import android.widget.ArrayAdapter;
08.import android.widget.AutoCompleteTextView;
09. 
10.public class MainActivity extends Activity {
11.    private AutoCompleteTextView autoComplete;
12. 
13.    @Override
14.    public void onCreate(Bundle icicle) {
15.        super.onCreate(icicle);
16.        setContentView(R.layout.main);
17.        autoComplete = (AutoCompleteTextView) findViewById(R.id.autoComplete);
18.        //設定自動填入的文字內容
19.        ArrayAdapter<string> adapter = new ArrayAdapter<string>(this,android.R.layout.simple_spinner_item,getContactsName());
20.        autoComplete.setAdapter(adapter);
21.    }
22. 
23.    //取得所有聯絡人姓名
24.    public String[] getContactsName() {
25.        //取得內容解析器
26.        ContentResolver contentResolver = this.getContentResolver();
27.        //設定你要從電話簿取出的欄位
28.        String[] projection = new String[]{Contacts.People.NAME,Contacts.People.NUMBER};
29.        //取得所有聯絡人
30.        Cursor cursor = contentResolver.query(Contacts.People.CONTENT_URI, projection, nullnull, Contacts.People.DEFAULT_SORT_ORDER);
31.        String[] contactsName = new String[cursor.getCount()];
32.        for (int i = 0; i < cursor.getCount(); i++) {
33.            //移到指定位置
34.            cursor.moveToPosition(i);
35.            //取得第一個欄位
36.            contactsName[i] = cursor.getString(0);
37.        }
38.        return contactsName;
39.    }
40.}
41.</string></string>


4. AndroidManifest.xml

01.<?xml version="1.0" encoding="UTF-8"?>
02.<manifest xmlns:android="http://schemas.android.com/apk/res/android"
03.     package="org.me.android_phonebook">
04.    <application>
05.         <activity android:name=".MainActivity" android:label="PhoneBook">
06.            <intent-filter>
07.                <action android:name="android.intent.action.MAIN"/>
08.                <category android:name="android.intent.category.LAUNCHER"/>
09.            </intent-filter>
10.        </activity>
11.    </application>
12.    <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
13.</manifest>


5. main.xml(Layout)


01.<?xml version="1.0" encoding="UTF-8"?>
02.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03.    android:orientation="vertical"
04.    android:layout_width="fill_parent"
05.    android:layout_height="fill_parent">"
06.    <AutoCompleteTextView
07.        android:id="@+id/autoComplete"
08.        android:layout_width="fill_parent"
09.        android:layout_height="50px">
10.    </AutoCompleteTextView>
11.</LinearLayout>


6. 執行之後的畫面。



 

 

 

arrow
arrow
    全站熱搜

    小犬 發表在 痞客邦 留言(0) 人氣()