Question

I want to use an AlertDialog in onOptionsItemSelected but I don't know which context to use. getApplication() and getApplicationContext() both don't work. Any ideas?

public boolean onOptionsItemSelected(MenuItem item) {

    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.actionbar_menu_info) {

        getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.container, new FragmentInfo())
            .commit();

    }
    else if (id == R.id.actionbar_menu_settings) {

      //            getSupportFragmentManager()
      //                .beginTransaction()
      //                .replace(R.id.container, new FragmentSettings())
      //                .commit();

        AlertDialog.Builder builder = new AlertDialog.Builder(get);
        builder.setIcon(getResources().getDrawable(R.drawable.quiz_ic_dialog_wrong));
        builder.setTitle(getResources().getString(R.string.ad_no_settings_in_free_version_title));
        builder.setMessage(getResources().getString(R.string.ad_no_settings_in_free_version_message));
        builder.setNeutralButton("Ok", null);
        builder.setCancelable(true);
        AlertDialog alert = builder.create();
        alert.show();

    }
    return super.onOptionsItemSelected(item);
}
Was it helpful?

Solution

Here's your answer :

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub

        switch (item.getItemId()) {

        case R.id.yourother_id:

            //Your Code!

            break;

        case R.id.your_id_thats_supposed_to_show_dialog:

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setIcon(getResources().getDrawable(R.drawable.ic_launcher));
            builder.setTitle(getResources().getString(R.string.hello_world));
            builder.setMessage(getResources().getString(R.string.hello_world));
            builder.setNeutralButton("Ok", null);
            builder.setCancelable(true);
            AlertDialog alert = builder.create();
            alert.show();

            break;

        default:
            break;
        }


        return super.onOptionsItemSelected(item);
    }

Hopefully this works..:)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top