机器人:从列表视图中删除的项目不能正常工作 [英] android: removing item from listview is not working properly
问题描述
我有两个textviews和一个按钮,这应该删除该行自定义适配器。
I have custom adapter with two textviews and one button, which should delete that row.
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;
}
}
}
问题是,当任何按钮pressed,它总是删除最后一排,而不是当前的。可变位置总是指向最后一行。
问题出在哪里?
problem is, when any button is pressed, it always removes last row, not the current one. Variable position always points at last row. Where is the problem ?
推荐答案
现在的问题是,当你做位置= POS;
你继续覆盖位置变量(因为getView()被调用的每一行,而你是你的滚动的ListView)。
The problem is that when you do position = pos;
you keep overriding the 'position' variable (since getView() gets called for each row while you are scrolling your ListView).
作为权宜之计,而是采用了位置的变量,你可以存储在你的 deleteButton
A行包含位置标记。例如这样的事情,在你的getView()方法:
As a quick fix, instead of using the 'position' variable, you could store in your deleteButton
a tag that contains the row position. For example something like this, in your getView() method:
deleteButton.setTag(pos);
然后在你的onClick()方法,你可以这样做:
Then in your onClick() method you can do:
int position = (int) v.getTag();
...
这篇关于机器人:从列表视图中删除的项目不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!