我想点击“删除”按钮从列表视图中删除一行。我的listview项目有以下水平放置的东西:TextView-1,TextView-2,TextView-3,ImageButton-delete按钮。现在,当我单击“删除”按钮时,应该从视图中删除该行。下面是适配器代码;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
View view = (View) v.getParent();
TextView tv = (TextView) view.findViewById(R.id.item_name);
String item = tv.getText().toString();
String tableno = mListItems.get(0).getTableNumber();
orderDetailsDB = new OrderDetailsDBAdapter(
getApplicationContext());
orderDetailsDB.deleteItem(item,tableno);
我尝试将个别文字视图设置为空白但不起作用。
holder.itemName.setText("");
holder.amount.setText("");
holder.quantity.setText("");
我阅读了几篇帖子,他们建议从我的列表中删除项目(mListItems),然后执行adapter.notifyDataSetChanged();
。问题是我没有使用数组适配器填充列表视图但使用自定义适配器,因此无法获取要删除的项目的位置。请指教。感谢。
答案 0 :(得分:6)
首先在适配器的getView
方法中写下以下行。
button.setTag(position)
onClick
方法中的
@Override
public void onClick(View v) {
int position = (Integer)v.getTag();
yourarraylistObject.remove(position);
// your remaining code
notifyDataSetChanged();
}
答案 1 :(得分:2)
只需使用remove()从适配器中删除列表项
供您参考
adapter = new MyListAdapter(this);
lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
答案 2 :(得分:0)
为了获得您想要删除的位置,您可以做的是将其传递给您的听众:
// inside custom adapter
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
.....
deleteButton.setOnClickListener(new MyClickListener(position);
}
private class MyClickListener implements OnClickListener
{
int position = -1;
public MyClickListener(final int position)
{
this.position = position;
}
@Override
public void onClick(View v) {
// do your delete code here
notifyDataSetChanged();
}