我有两个textview和一个按钮的自定义适配器,应删除该行。
public class ListViewAdapter extends ArrayAdapter<OneRowListView> implements OnClickListener {
private ArrayList<OneRowListView> items;
private ContactsActivity ca;
private int position;
private OneRowListView o;
public ListViewAdapter(Context context, int textViewResourceId, ArrayList<OneRowListView> items) {
super(context, textViewResourceId, items);
this.items = items;
ca = (ContactsActivity) context;
}
@Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
position = pos;
if (v == null) {
LayoutInflater vi = (LayoutInflater)ca.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.one_item_contacts_list, null);
}
o = items.get(position);
if (o != null) {
TextView name = (TextView) v.findViewById(R.id.name);
TextView surname = (TextView) v.findViewById(R.id.surname);
TextView phoneNumber = (TextView) v.findViewById(R.id.phonenumber);
Button deleteButton = (Button) v.findViewById(R.id.deleteButton);
deleteButton.setOnClickListener(this);
// ...
}
return v;
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.deleteButton:
remove(items.remove(position));
notifyDataSetChanged();
break;
}
}
}
问题是,当按下任何按钮时,它总是删除最后一行,而不是当前行。可变位置始终指向最后一行。 问题在哪里?
答案 0 :(得分:1)
问题是当你执行position = pos;
时,你会继续覆盖'position'变量(因为在滚动ListView时,每行都会调用getView())。
作为快速修复,您可以在deleteButton
包含行位置的标记中存储,而不是使用'position'变量。例如,在你的getView()方法中这样的东西:
deleteButton.setTag(pos);
然后在你的onClick()方法中你可以这样做:
int position = (int) v.getTag();
...