Search code examples
androidandroid-studiodialogoverflow-menu

Android: Launching an alert dialog from an overflow menu item


I am trying to launch an alert dialog from an overflow menu item. The dialog layout is in dialog_settings.xml.

import android.support.v7.app.AlertDialog;

/** Code omitted */

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId():
        if (id == R.id.action_settings) {
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
            View mView = getLayoutInflater().inflate(R.layout.dialog_settings, null);
        }
        return super.onOptionsItemSelected(item);
    }

The code above creates no errors but clicking the menu item produces no dialog either. I am using Android 4.1.2, API 16 for my app and Android Studio.

I hope to find a simpler solution than in this question from 2012.


Solution

  • You are just building the dialog but not creating and showing it. Maybe you want something like this:

    if(id == R.id.action_settings) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(R.layout.dialog_settings) //set the view
           .create() //create the dialog
           .show(); //show the dialog
    
        return true;
    }