My ListViewItems have delete buttons in them. From those button’s click events I want to show a confirmation dialog before deleting the item via it’s ID from the database. The ID is stored in the item’s ViewHolder.
How can I access the item’s ViewHolder from the AlertDialog’s click handler? Here is the relevant code. Compiler chokes on “V” inside onClick(DialogInterface dialog, int whichButton).
I could store the ID in the button’s tag but that feels awkward.
I’m targetting minimum API level 8 but let me know if higher API levels have a solution for this. It’s my first Android program so there may very well be an obvious solution.
private static class MyAdapter extends CursorAdapter {
//.....
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = View.inflate(context, R.layout.my_detail, null);
MyViewHolder holder = new MyViewHolder();
holder.deleteButton = (Button) view.findViewById(R.id.deleteButton);
holder.deleteButton.setOnClickListener(deleteButtonClickListener);
holder.editButton = (Button) view.findViewById(R.id.editButton);
holder.editButton.setOnClickListener(editButtonClickListener);
holder.nameTextView = (TextView) view
.findViewById(R.id.nameTextView);
holder.itemId = cursor.getLong(cursor
.getColumnIndex(MyData.ID_COLUMN));
view.setTag(holder);
return view;
} // newView()
//.....
private OnClickListener deleteButtonClickListener = new OnClickListener() {
public void onClick(View v) {
new AlertDialog.Builder(_context)
.setTitle("Delete?")
.setMessage("Delete item?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
MyViewHolder holder = (MyViewHolder) ((View) v
.getParent()).getTag();
long itemId = holder.itemId;
_MyData.deleteItem(itemId);
}
}).setNegativeButton(android.R.string.no, null)
.show();
} // onClick()
}; // deleteButtonClickListener
//.....
}
Your code actually looks pretty good, the only change needed is that
vneeds to be declaredfinal, like so:The reason for this is due to how Java implements closures.
vshould befinalso that our implementation ofDialogInterface.OnClickListenerin thesetPositiveButton()has access to the variable.