步骤 1. 在 xml 文件中创建自动完成功能,如下所示
<AutoCompleteTextView android:paddingTop="15dp"
android:id="@+id/txtPhoneNo"
android:focusableInTouchMode="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"/>
步骤 2. 在您的 Android Mainfeast 文件中添加以下权限以访问联系人
<uses-permission android:name="android.permission.READ_CONTACTS" />
步骤 3. 创建一个 Activity 并在您的 Java 代码中映射 autocompletetextview 组件
public class MyContacts extends Activity {
AutoCompleteTextView txtPhoneNo;
public ArrayList<String> c_Name = new ArrayList<String>();
public ArrayList<String> c_Number = new ArrayList<String>();
String[] name_Val=null;
String[] phone_Val=null;
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
txtPhoneNo = (AutoCompleteTextView) findViewById(R.id.txtPhoneNo);
}
第 4 步:使用 ContentReslover 获取联系人,如果您在 Android 1.6 或之前的版本中运行它,请使用人员类获取联系人并将联系人添加到数组列表中,如下所示
ContentResolver cr1 = getContentResolver();
String[] projection = new String[] { People._ID,People.NAME,People.NUMBER };
Uri phone_contacts = People.CONTENT_URI;
Cursor managedCursor = cr1.query(phone_contacts, projection, null, null, People.NAME + " ASC");
if (managedCursor.moveToFirst()) {
String contactname;
String cphoneNumber;
int nameColumn = managedCursor.getColumnIndex(People.NAME);
int phoneColumn = managedCursor.getColumnIndex(People.NUMBER);
Log.d("int Name",Integer.toString(nameColumn));
Log.d("int Number",Integer.toString(phoneColumn));
do {
// Get the field values
contactname = managedCursor.getString(nameColumn);
cphoneNumber = managedCursor.getString(phoneColumn);
if((contactname != " " || contactname != null) && (cphoneNumber!= " " ||cphoneNumber!= null))
{
c_Name.add(contactname);
c_Number.add(cphoneNumber);
}
} while (managedCursor.moveToNext());
}
// Donot use People class if your using android1.6 above
Uri contacts = Uri.parse("content://icc/adn");
Cursor managedCursor1 =cr.query(contacts, null, null, null, null);
if (managedCursor1.moveToFirst()) {
String contactname;
String cphoneNumber;
int nameColumn = managedCursor1.getColumnIndex("name");
int phoneColumn = managedCursor1.getColumnIndex("number");
Log.d("int Name",Integer.toString(nameColumn));
Log.d("int Number",Integer.toString(phoneColumn));
do {
// Get the field values
contactname = managedCursor1.getString(nameColumn);
cphoneNumber = managedCursor1.getString(phoneColumn);
if((contactname != " " || contactname != null) && (cphoneNumber!= " " ||cphoneNumber!= null))
{
c_Name.add(contactname);
c_Number.add(cphoneNumber);
}
} while (managedCursor1.moveToNext());
}
第 5 步:现在将 ArrayList 转换为 Array 并将该 Array 设置为 AutoComplete,如下所示
name_Val = (String[]) c_Name.toArray(new String[c_Name.size()]);
phone_Val= (String[]) c_Number.toArray(new String[c_Name.size()]); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, name_Val);
txtPhoneNo.setAdapter(adapter);