- }
解析
1.在main.xml中添加两个TextView
用于显示"Name:"的静态标签
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Name: "
- />
用于动态添加并显示联系人的姓名内容的TextView
- <TextView
- android:id="@+id/row_entry"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
2.修改LinearLayout的布局方向
- androidrientation="horizontal" //说明横向排布
3.AndroidManifest.xml中说明使用权限
- <uses-permission
- android:name="android.permission.READ_CONTACTS"></uses-permission>
- //说明可以访问读取联系人信息
- <uses-permission
- android:name="android.permission.CALL_PHONE"></uses-permission>
- //说明可以使用打电话功能
4.Java代码中的读取联系人信息处理
- try {
- Cursor c =
- getContentResolver().query(People.CONTENT_URI, null,null, null, null);
- //Cursor,该接口提供从数据库提取信息返回结果中随机读写访问
- //ContentResolver 提供应用程序访问Content模型
- //ContentResolver.query()抽取给定的URI,返回一个在结果之上的Cursor
- startManagingCursor(c);
- //该方法允许Activity基于Activity的生命周期来为你处理管理给定的Cursor的生命周期
- name = new String[] { People.NAME };
- //新建用户名数组 People类用于列出联系人 People.NAME得到联系人姓名
- to = new int[] { R.id.row_entry };
- //创建一个TextView引用数组 用来放置获取的 People.NAME
- sadapter = new SimpleCursorAdapter(this,R.layout.main, c, name, to);
- this.setListAdapter(sadapter);
- //创建一个简单的适配器从一个cursor指针到TextView或是ImageView的map专栏适配器。
- //构造方法(Context,layout,Cursor,from,to),第一参数是设备上下文,第二个参数是布局文件,第三个参数是指向联系人URI的Cursor指针,form代表来源的字符串(联系人名),to把联系人名放到的地方(TextView)
- } catch (Exception e) {
- Toast.makeText(this, "联系人读取错误",Toast.LENGTH_LONG).show();
- //Toast显示提示,不打扰用户。.show()用来显示Toast
- }
5.Java代码中的点击事件处理(选择后电话联系该联系人)
- protected void onListItemClick(ListView l,View v, int position, long id) {
- // TODO Auto-generated method stub
- super.onListItemClick(l, v, position, id);
- callIntent=new Intent(Intent.ACTION_CALL);
- //创建一个带有Call动作的Intent
- Cursor c=(Cursor)sadapter.getItem(position);
- //通过选中的Items位置来获取相应的联系人指针 Cursor
- PhoneID=c.getLong(c.getColumnIndex(People.PRIMARY_PHONE_ID));
- //获取相应联系人电话号码
- //getLong()返回请求数据的一个长整型
- //为给定的列,返回基于0的索引值
- //People.PRIMARY_PHONE_ID 获取主键电话号码
- callIntent.setData(ContentUris.withAppendedId(android.provider.
- Contacts.Phones.CONTENT_URI, PhoneID));
- //为Intent设置操作的数据
- //ContentUris操作带有数据内容的Uri的实用方法、它们带有"Content"体制
- //withAppendedId()把给定的ID添加到path后面 第一个参数是开始的,后面参数是添加的
- startActivity(callIntent);
- //开启Intent
- }
本文转自xyz_lmn51CTO博客,原文链接:
http://blog.51cto.com/xyzlmn/819251
,如需转载请自行联系原作者