Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android BaseAdapter应用

Android BaseAdapter应用实例

作者:hshm20517

这篇文章主要介绍了Android BaseAdapter应用方法,结合生成联系人Items的实例形式分析了BaseAdapter的使用技巧,需要的朋友可以参考下

本文实例讲述了Android BaseAdapter的应用方法。分享给大家供大家参考,具体如下:

直接上源码

/**
* 生成联系人Items,即Items中包含如下控件
*
*/
public final class ViewHolder{
  public ImageView callImg;//打电话的图标
  public ImageView headImg;//头像
  public TextView peopleName;//联系人名
  public TextView peopleNumber;//联系人号码
}
public class MyAdapter extends BaseAdapter {
 private LayoutInflater mInflater;
 public MyAdapter(Context context) {
  this.mInflater = LayoutInflater.from(context);
 }
 public int getCount() {
   return listPeople.size();
 }
 public Object getItem(int arg0) {
   return listPeople.get(arg0);
 }
 public long getItemId(int arg0) {
  return arg0;//当初在看别人例子时,此处返回NUll,加载都没问题,但在ListView中的OnItemsClick事件中就报错了。
 }
 public View getView(final int position, View convertView,
  ViewGroup parent) {
  ViewHolder holder = null;
  if (convertView == null) {
  holder = new ViewHolder();
  convertView = mInflater.inflate(R.layout.peopleinfo, null);
  holder.callImg = (ImageView) convertView
   .findViewById(R.id.callbtn);
  holder.headImg = (ImageView) convertView
   .findViewById(R.id.contactImage);
  holder.peopleName = (TextView) convertView
   .findViewById(R.id.peopleName);
  holder.peopleNumber = (TextView) convertView
   .findViewById(R.id.peopleNumber);
  convertView.setTag(holder);
  } else {
  holder = (ViewHolder) convertView.getTag();
  }
  final String name = (String) listPeople.get(position).get(
   "peopleName");
  final String num = (String) listPeople.get(position).get(
   "peopleNumber");
  holder.peopleName.setText((String) listPeople.get(position).get(
   "peopleName"));
  holder.peopleNumber.setText((String) listPeople.get(position).get(
   "peopleNumber"));
  //  holder.headImg.setImageResource(R.drawable.ic_menu_contact);
  if(listPeople.get(position).get("peoplePhoto") != null){
  holder.headImg.setImageBitmap((Bitmap)listPeople.get(position).get(
  "peoplePhoto"));
  }
  holder.callImg.setImageResource(R.drawable.ic_dial_action_call);
  holder.callImg.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
  //处理Items中控件的触发事件
  }
  });
  return convertView;
 }
 }
/*
*应用BaseAdapter
*
*/
final MyAdapter myAdapter = new MyAdapter(this);
  contacts.setAdapter(myAdapter);
  contacts.setOnItemClickListener(new OnItemClickListener() {
  @SuppressWarnings("unchecked")
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
   long arg3) {
   Map<String, Object> map = (Map<String, Object>) myAdapter.getItem(arg2);//此处需要注意,
   String peopleNumber = String.valueOf(map.get("peopleNumber"));
  }
});

希望本文所述对大家Android程序设计有所帮助。

您可能感兴趣的文章:
阅读全文