遗留问题:获取头像及其他信息
利用adapter和Cursor来获取联系人的姓名和手机号,重在复习之前学过的内容加深自己的理解.
其中需要注意的部分:
1.adapter中的getview的优化问题,用到tag这一属性
2.onBackPressed()返回方法的重写,使得程序更加人性化
下面是主要代码
1.adapter
public class MyAdapter extends BaseAdapter {private List<PhoneInfo> data;private Context context;public MyAdapter(List<PhoneInfo> data,Context context) {this.data = data;this.context = context;}@Overridepublic int getCount() {return data.size();}@Overridepublic PhoneInfo getItem(int position) {return data.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {phonedemo demo;if (convertView==null) {convertView = LayoutInflater.from(context).inflate(R.layout.cell, null);demo = new phonedemo();demo.name = (TextView) convertView.findViewById(R.id.name);demo.number = (TextView) convertView.findViewById(R.id.number);demo.img = (ImageView) convertView.findViewById(R.id.imageView1);demo.name.setText(data.get(position).getName());demo.number.setText(data.get(position).getNumber());
// demo.img.setImageResource(data.get(position).getId());//利用tag达到循环利用资源convertView.setTag(demo);}else {//利用tag达到循环利用资源demo = (phonedemo) convertView.getTag();demo.name.setText(data.get(position).getName());demo.number.setText(data.get(position).getNumber());
// demo.img.setImageResource(data.get(position).getId());}return convertView;}public static class phonedemo{TextView name,number;ImageView img;}
}
2.获取联系人
// 用于存储封装的联系人的集合public static List<PhoneInfo> data = new ArrayList<PhoneInfo>();/*** 获取联系人数据,包括名字和号码,后期添加其他信息* * @param context*/public static void getcontact(Context context) {// getContentResolver()搜索系统的数据库,query相当于设置搜索条件// 这里是全部搜索Cursor cursor = context.getContentResolver().query(Phone.CONTENT_URI,null, null, null, null);String name;String number;while (cursor.moveToNext()) {// 获取搜索结果的信息,通过对应的字段值来获取name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));number = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));// 将获取的结果加入集合中data.add(new PhoneInfo(name, number));}}
3,返回方法
private long lasttime = 0;@SuppressLint("NewApi")@Overridepublic void onBackPressed() {if (lasttime<=0) {Toast.makeText(this, "再次点击返回", Toast.LENGTH_SHORT).show();lasttime = System.currentTimeMillis();}else {long currenttime = System.currentTimeMillis();if (currenttime-lasttime<1000) {//带有动画的返回finishAfterTransition();}else {Toast.makeText(this, "再次点击返回", Toast.LENGTH_SHORT).show();lasttime = System.currentTimeMillis();}}}
版权声明:本文为博主原创文章,未经博主允许不得转载。