在ListView中多个item里面的按钮,获取不到当前item的位置

来源:互联网 发布:js 微信分享demo 编辑:程序博客网 时间:2024/05/16 00:40

在做这个项目的时候,碰到了这样的问题,在给ListView中的Button增加点击事件的时候,修改的东西总是多条数据的最后一条,也就是说,无论点击哪一行的Button,触发的事件总是最后一行,在网上搜了一下,大致知道怎么解决这个问题。

1.首先在定义控件的时候,设置一个Tag标记,将getView(int position, View convertView, ViewGroup parent)方法的position记录下来;

2.然后在按钮的onClick(View v)方法中,利用v对象获取在第一步中设置的Tag标记,也就是保存的位置,通过位置,可以从列表集合里获取到相应的值(像id等能作为唯一标识的值),再对相应id的对象进行操作就不会出错了。

我的源码示例如下:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
holder.sentBT = (Button)convertView.findViewById(R.id.contact_home_lv_item_center_bt);
//下面这行代码是解决问题的关键
holder.sentBT.setTag(position);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
final Contacts contact = failedContacts.get(position);
final PresentGoods pGoods = contact.goods;
holder.telTV.setText(pGoods.phoneNum);
//点击按钮
holder.sentBT.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
int pos = (Integer) v.getTag();
Contacts contacts = (Contacts) getItem(pos);
PresentGoods p = contacts.goods;
//写你自己的代码

}
});

return convertView;
}

private class ViewHolder{
Button sentBT;
}

说了这么多,大家看明白了吗?

0 0