我有一个列表视图,它有一个文本视图和一个图像按钮(删除)。当我单击图像按钮时,该行被删除并且列表视图被更新。
一切工作正常,但问题是当列表视图中有不止一行时,删除一行后,我无法删除另一行,因为位置值不合适。
说清楚,例如:列表视图中有 3 行。
- 我单击要删除的第一行(位置值为 0),它被删除并且列表视图被更新。
所以现在有两行,
- 我再次单击第一行,但删除失败。(因为 listview 没有更新位置值,实际上现在它的位置值应该是 0,而是显示 1,有时显示 2)
这是我的代码,
CustomListView.class
public View getView(final int position, View convertView, ViewGroup parent) {
holder = null;
DataFields rowItems = (DataFields) getItem(position);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.home_field_row, null);
holder = new ViewHolder();
holder.dataFields = items.get(position);
holder.mName = (TextView) convertView
.findViewById(R.id.hmFieldName);
holder.mDeleteImage = (ImageView) convertView
.findViewById(R.id.hmFieldDeleteImage);
holder.mDeleteImage.setTag(position);
holder.mDeleteImage
.setOnClickListener(new ImageView.OnClickListener() {
@Override
public void onClick(final View v) {
Log.d("POSITION****", String.valueOf(position));
final Integer index = (Integer) v.getTag();
holder.dataFields = items.get(position);
value = holder.dataFields.getId();
int status = dbHandler
.deleteField(holder.dataFields);
if (status != 0) {
items.remove(index.intValue());
notifyDataSetChanged(); //ListView is getting updated but not the position values of rows
} else {
Toast.makeText(getContext(),
"Failed to delete !",
Toast.LENGTH_SHORT).show();
}
}
});
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.mName.setText(rowItems.getName());
return convertView;
}
非常感谢任何形式的帮助。谢谢 !
已编辑
正如你们所说,我做了以下更改,但位置值仍然没有更新......
holder.dataFields = items.get(position);
DataFields obj = items.get(position);
value = holder.dataFields.getId();
int status = dbHandler.deleteField(holder.dataFields);
if (status != 0) {
items.remove(index.intValue());
HomeActivity.mAdapter.remove(obj); //I also tried items.remove(obj);
HomeActivity.mAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getContext(), "Failed to delete !", Toast.LENGTH_SHORT).show();
}