我有一个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());
}
我知道上面的代码不起作用(并且它没有工作,正如预期的那样我得到一个空指针异常),所以如果有人可以指导我如何做到这一点,那将是很多帮助..
答案 0 :(得分:0)
在onItemClick中更改此内容
ContactViewHolder view = (ContactViewHolder ) arg1.getTag();
String number = view.getPhNumber();
并在ViewHolder中添加
public class ContactViewHolder {
ImageView imgContact;
TextView txtViewContactName;
TextView txtViewPhoneNumber;
String phNumber;
public String getPhNumber() {
return phNumber;
}
}
在getView()
中添加它String phoneNumber = curObj.getString(curObj.getColumnIndex("number"));
phNumber = phoneNumber ;
为剩余的参数添加相同的代码。它会起作用。
答案 1 :(得分:0)
您可以在setOnItemClickListener
以及setOnClickListener
中获取自定义网格项。
public ImageView img;
your_grid.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, final int position, long id)
{
img = (ImageView)v.findViewById(R.id.grid_item_image);
}
});