乐读文学

Android从入门到精通

乐读文学 > 科普学习 > Android从入门到精通

第131页

书籍名:《Android从入门到精通》    作者:明日科技




ContentResolver  resolver  =  getContentResolver();  //获得ContentResolver对象



Cursor  cursor  =  resolver.query(Contacts.CONTENT_URI,  null,  null,  null,  null);//查询记录



while  (cursor.moveToNext())  {



int  idIndex  =  cursor.getColumnIndex(columns[0]);  //获得ID值的索引



int  displayNameIndex  =  cursor.getColumnIndex(columns[1]);  //获得姓名索引



int  id  =  cursor.getInt(idIndex);  //获得id



String  displayName  =  cursor.getString(displayNameIndex);  //获得名称



Cursor  phone  =  resolver.query(Phone.CONTENT_URI,  null,  columns[3]  +  "="  +  id,  null,  null);



while  (phone.moveToNext())  {



int  phoneNumberIndex  =  phone.getColumnIndex(columns[2]);  //获得电话索引



String  phoneNumber  =  phone.getString(phoneNumberIndex);  //获得电话



sb.append(displayName  +  ":  "  +  phoneNumber  +  "\n");  //保存数据



}



}



cursor.close();/  //关闭Cursor



return  sb.toString();



}



}

(3)在AndroidManifest文件中增加读取联系人记录的权限,代码如下:



运行本实例,其效果如图11.7所示。



图11.7 显示联系人姓名和电话

11.4.2 自动补全联系人姓名

例11.3   在Eclipse中创建Android项目,名称为11.3,实现自动补全联系人姓名的功能。(实例位置:光盘\TM\sl\11\11.3)

(1)修改res\layout\main.xml文件,设置背景图片和标签属性,并增加一个自动补全标签,代码如下:








android:layout_width="fill_parent"



android:layout_height="fill_parent"



android:background="@drawable/background"



android:orientation="vertical"  >






android:id="@+id/title"



android:layout_width="wrap_content"



android:layout_height="wrap_content"



android:layout_gravity="center"



android:text="@string/title"



android:textColor="@android:color/black"



android:textSize="30dp"  />






android:layout_width="match_parent"



android:layout_height="wrap_content"



android:orientation="horizontal"  >






android:id="@+id/textView"



android:layout_width="wrap_content"



android:layout_height="wrap_content"



android:layout_margin="5dp"



android:text="@string/name"



android:textColor="@android:color/black"



android:textSize="25dp"  />






android:id="@+id/edit"



android:layout_width="match_parent"



android:layout_height="wrap_content"



android:completionThreshold="1"



android:textColor="@android:color/black"  >

















注意:  android:completionThreshold属性用于设置输入几个字符时给出提示。

(2)创建ContactListAdapter类,它继承了CursorAdapter类并实现了Filterable接口,在重写方法时完成了获取联系人姓名的功能,代码如下:

public  class  ContactListAdapter  extends  CursorAdapter  implements  Filterable  {



private  ContentResolver  resolver;



private  String[]  columns  =  new  String[]  {  Contacts._ID,  Contacts.DISPLAY_NAME  };



public  ContactListAdapter(Context  context,  Cursor  c)  {



super(context,  c);  //调用父类构造方法



resolver  =  context.getContentResolver();  //初始化ContentResolver



}



@Override



public  void  bindView(View  arg0,  Context  arg1,  Cursor  arg2)  {



((TextView)  arg0).setText(arg2.getString(1));



}



@Override