通过警报对话框删除列表视图项

时间:2018-04-13 14:12:11

标签: java android android-studio alertdialog

我试图建立一个警告对话框,删除ListView中的项目,但我无法找到解决方法。 这是我的代码:

contactsListView.setLongClickable(true);
    contactsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            AlertDialog.Builder builder = new AlertDialog.Builder(ContactsActivity.this);
            builder.setTitle("Contact Removal");
            builder.setMessage("Are you sure you want to remove this contact?");
            builder.setCancelable(false);
            builder.setPositiveButton("Yes, I'm sure!", new HandleAlertDialogListener());
            builder.setNegativeButton("No, I've changed my mind", new HandleAlertDialogListener());
            AlertDialog dialog = builder.create();
            dialog.show();
            return true;
        }
    }); 

这是我的HandleAlertDialogListener()

private class HandleAlertDialogListener implements DialogInterface.OnClickListener {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
}

问题是我无法提及我想删除的项目的位置。 另一个问题是对话框按钮的值是什么? 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

在你的onItemLongClick()中,让你的位置参数最终,然后像这样创建你的警告对话框:

new AlertDialog.Builder(this).setTitle("Delete").setMessage("Review").setPositiveButton(R.string.positive_delete, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int id) {
          // use position here.
        }
      }).setNegativeButton(R.string.negative_reask, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int id) {
          dialog.dismiss();
        }
      }).create().show();

希望这有帮助!

答案 1 :(得分:0)

我猜你有一个适配器来显示ListView中的项目吗?

如果是这样,你应该删除像我说的那样的项目:

myDataList.remove(position);
myAdapter.notifyDataSetChanged();

其中position是此方法中的属性:

onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
相关问题