我有一个列表视图,其中包含多个列表项。每个列表项都有一个编辑或删除按钮,但问题是当我点击任何列表项的编辑或删除按钮时,它会获取最后一个列表项的id或数据。例如:我有3个项目说id 102,104,105,如果我想编辑id 102的数据,那么它获取最后一项的数据并更新它。我无法理解为什么它不能正常工作。适配器的代码
//代码
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public int getItemViewType(int position) {
return position;
}
public int getViewTypeCount() {
return 1;
}
@Override
public int getCount() {
return this.addressModelList.size();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.item_show_all_address, parent, false);
viewHolder.txtUserName = (TextView) convertView.findViewById(R.id.userName);
viewHolder.txtUser_phone =(TextView) convertView.findViewById(R.id.user_phone);
viewHolder.txtLocation = (TextView) convertView.findViewById(R.id.location);
viewHolder.txt_edit_address = (TextView) convertView.findViewById(R.id.txt_edit_address);
viewHolder.txt_deleteAddress = (TextView) convertView.findViewById(R.id.txt_deleteAddress);
sp = mContext.getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
addressModel = addressModelList.get(position);
viewHolder.txtUserName.setText(sp.getString("firstName",null)+" "+sp.getString("lastName",null));
viewHolder.txtUser_phone.setText(addressModel.getAddPhoneNumber() + "#" +addressModel.getAddressId()+"*" +position);
viewHolder.txtLocation.setText(addressModel.getAddLocation());
viewHolder.txt_edit_address.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("TAG", "editAddress: "+addressModel.getAddressId() +"**" +position);
showAllAddresses.editAddress(addressModel.getAddressId(),addressModel.getAddLocation(),addressModel.getAddPhoneNumber());
}
});
viewHolder.txt_deleteAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showAllAddresses.deleteAddress(addressModel.getAddressId());
}
});
result = convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
// lastPosition = position;
return convertView;
}
}
在编辑或删除监听器时需要第一次使用正确的id然后获取最后一个id的值。 请帮忙
答案 0 :(得分:1)
在OnClickListener中获取addressModel
viewHolder.txt_edit_address.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addressModel = addressModelList.get(position);
Log.e("TAG", "editAddress: "+addressModel.getAddressId() +"**" +position);
showAllAddresses.editAddress(addressModel.getAddressId(),addressModel.getAddLocation(),addressModel.getAddPhoneNumber());
}
});
viewHolder.txt_deleteAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addressModel = addressModelList.get(position);
showAllAddresses.deleteAddress(addressModel.getAddressId());
}
});