Reputation: 117
I'm attempting to make an alert dialog remove an item in a ListView but I can't find a solution to how I do it. Here is my code:
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;
}
});
Here is my HandleAlertDialogListener()
private class HandleAlertDialogListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}
the problem is that I can't refer to the position of the item I want removed. Another question is what are the which values for the dialog's buttons? Any help would be appreciated.
Upvotes: 1
Views: 270
Reputation: 578
I guess you have an Adapter to show items in a ListView?
If so, you should delete an item like I said:
myDataList.remove(position);
myAdapter.notifyDataSetChanged();
Where position is an attribute in this method:
onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Upvotes: 0
Reputation: 1320
In your onItemLongClick() make your position parameter final , then create your alert dialog like this :
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();
Hope this helps!
Upvotes: 2