我有一个 gridview,它使用自定义适配器填充联系人的信息(图像、姓名和电话号码)。单击特定项目时,我想检索联系人的信息(图像信息、姓名和电话号码)。我知道我必须使用 setTag() 和 getTag() 但我不知道该怎么做。这是我的代码..
自定义适配器的getView方法
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ContactViewHolder contactViewHolder;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
convertView = li.inflate(R.layout.activity_grid_one_item, null);
contactViewHolder = new ContactViewHolder();
contactViewHolder.imgContact = (ImageView) convertView
.findViewById(R.id.imgViewContactImage);
contactViewHolder.txtViewContactName = (TextView) convertView
.findViewById(R.id.txtViewContactName);
contactViewHolder.txtViewPhoneNumber = (TextView) convertView
.findViewById(R.id.txtViewPhoneNumber);
convertView.setTag(contactViewHolder);
} else {
contactViewHolder = (ContactViewHolder) convertView.getTag();
}
curObj.moveToPosition(position);
String name = curObj.getString(curObj.getColumnIndex("name"));
if (name != null)
contactViewHolder.txtViewContactName.setText(name);
else
contactViewHolder.txtViewContactName.setText("Unknown");
String phoneNumber = curObj.getString(curObj.getColumnIndex("number"));
if (phoneNumber != null)
contactViewHolder.txtViewPhoneNumber.setText(phoneNumber);
else
contactViewHolder.txtViewPhoneNumber.setText("Unknown");
String image = curObj.getString(curObj.getColumnIndex("image"));
if(image.equalsIgnoreCase("R.drawable.addcontactsmall2"))
contactViewHolder.imgContact.setImageResource(R.drawable.addcontactsmall2);
else
{
Uri uri = Uri.parse(image);
contactViewHolder.imgContact.setImageURI(uri);
}
return convertView;
}
public class ContactViewHolder {
ImageView imgContact;
TextView txtViewContactName;
TextView txtViewPhoneNumber;
}
onItemClick
方法
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
View view = (View) arg1.getTag(arg2);
TextView txtPhoneNumber = (TextView) view.findViewById(R.id.txtview_addcontact_phonenumber);
System.out.println(txtPhoneNumber.getText().toString());
}
我知道上面的代码不起作用,(它也不起作用,正如预期的那样,我得到一个空指针异常),所以如果有人能指导我如何做到这一点,那将会有很大帮助..