开发者

How to pass data from context menu to alert dialog in Android?

开发者 https://www.devze.com 2023-04-09 07:50 出处:网络
The method below happens when an item in a ListActivity is long pressed. The idea is to delete that item from the database and for that I need to call mNotesAdapter.deleteNote(ID). Which works fine if

The method below happens when an item in a ListActivity is long pressed. The idea is to delete that item from the database and for that I need to call mNotesAdapter.deleteNote(ID). Which works fine if I don't use an AlertDialog; but I should use one for delete confirmations. But I don开发者_StackOverflow社区't know how to pass the menu info, or the id itself to the onClick method.

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo();

    switch (item.getItemId()) {
        case R.id.contextmenu_item_remove:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.setMessage("Are you sure you want to delete this note?");

            builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    // VARIABLE menuInfo IS NOT ACCESSIBLE HERE, NOW WHAT?
                    mNotesAdapter.deleteNote(menuInfo.id);
                }
            });

            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });

            builder.show();

            return true;
    }

    return super.onContextItemSelected(item);
}


You should be able to access the reference if you mark it as final.

To answer the other question in your comment, final doesn't mean the contents of the object can't be changed. It just means that the reference can't move to another object.

When you enter that method, you're immediately creating a new reference to a new AdapterContextMenuInfo in the first line. Then you're creating a new OnClickListener that will only act on that one object that menuInfo is creating.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号