我想使用OnItemLongClickListener从ListView中删除一个项目 这是我在OnLongClick项目时出现AlertDialog的代码 我还需要在删除项目时使用哪些代码
public class DeleteItem extends Activity {
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = (ListView) findViewById(R.id.listView);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
AlertDialog.Builder alert = new AlertDialog.Builder(DeleteItem.this);
alert.setMessage("Are you sure you want to delete this?");
alert.setCancelable(false);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Here I need the delete code
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return false;
}
});
}
}
答案 0 :(得分:0)
ArrayAdapter的方法为remove(int index)
:
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(final AdapterView<?> arg0, View arg1,
final int position, long arg3) {
AlertDialog.Builder alert = new AlertDialog.Builder(DeleteItem.this);
alert.setMessage("Are you sure you want to delete this?");
alert.setCancelable(false);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ArrayAdapter yourArrayAdapter = (ArrayAdapter) arg0.getAdapter();
yourArrayAdapter.remove(position);
yourArrayAdapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return false;
}
});
使用适配器的通用类型调整强制转换。仅当您向适配器提供元素集合时,它才有效。如果你提供了一个数组,它将抛出异常