Kev
Kev

Reputation: 173

Android: Context Menu to Alert dialog

What do i need to change to make this display into alert dialog?

@Override
        public void onCreateContextMenu(ContextMenu menu, View v,
                ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);
            menu.add(0, DELETE_ID, 0, R.string.menu_delete);
        }

        @Override
        public boolean onContextItemSelected(MenuItem item) {
            switch(item.getItemId()) {
                case DELETE_ID:
                    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                    mDbHelper.deleteNote(info.id);
                    fillData();
                    return true;
            }
            return super.onContextItemSelected(item);
        }

I'm a beginner in android so i still don't know how to implements some things. I want this to appear as alert dialog. Currently the user needs to longkeypress to activate the delete. However i want to prompt it as an alert dialog and have choices for the user to choose from if he wants to really delete it or not.

Upvotes: 1

Views: 5361

Answers (2)

Brave
Brave

Reputation: 367

You only need to implement the following function. It will work.

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
{
Log.e(LOGTAG, "Tao menu");
if(v == expList)
{
    super.onCreateContextMenu(menu, v, menuInfo);
    //AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;

    // We know that each row in the adapter is a Map
    //HashMap map =  (HashMap) simpleAdpt.getItem(aInfo.position);
    menu.setHeaderTitle("Options");
    menu.add(1, 1, 1, "Reprint");
    menu.add(1, 2, 1, "Void");

    menu.getItem(0).setOnMenuItemClickListener(new OnMenuItemClickListener()
    {
        public boolean onMenuItemClick(MenuItem clickedItem)
        {

            return true;
        }
    });

    menu.getItem(1).setOnMenuItemClickListener(new OnMenuItemClickListener()
    {
        public boolean onMenuItemClick(MenuItem clickedItem)
        {

            return true;
        }
    });
}

}

Upvotes: 1

sgarman
sgarman

Reputation: 6182

In your case DELETE_ID do this:

    new AlertDialog.Builder(this).setTitle("Confirm Delete")
        .setMessage("Do you want to delete this blank?")
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteNote(info.id);
                fillData();
            }
        })
        .setNeutralButton("Cancel", null) // don't need to do anything but dismiss here
        .create()
        .show();

You need to put the delete logic in the OK click listener.

Upvotes: 3

Related Questions