如何使用 AlertDialog 从 listView 中删除项目?

How can i delete an item from a listView using AlertDialog?

大家好,我正在尝试创建一个带有 2 个按钮的警告对话框。一个返回主屏幕,另一个从我的列表视图中删除项目并返回主屏幕。我尝试了几种方法,但 none 似乎有效。有人可以帮忙吗?这是我的代码。

@Override public void onItemClick(AdapterView<?> parent,
                                  View view, int position, long id) {

    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle("Hello My Name is");
    alertDialog.setMessage("" + mNameList.get(position));
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
        }
    });
    alertDialog.setButton2("Remove", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

            Toast.makeText(getApplicationContext(), "Removed from list", Toast.LENGTH_SHORT).show();
        }
    });

    alertDialog.show();
}

如有任何帮助,我们将不胜感激。提前致谢!

你可以这样做

alertDialog.setButton2("Remove", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        mNameList.remove(position);//or equalalent of remove method
        yourAdapter.notifyDataSetChange();
        Toast.makeText(getApplicationContext(), "Removed from list", Toast.LENGTH_SHORT).show();

    }
});