在onOptionsItemSelected中使用哪个上下文?

时间:2014-03-22 00:21:14

标签: android this alert android-context

我想在AlertDialog中使用onOptionsItemSelected,但我不知道要使用哪种上下文。 getApplication()getApplicationContext()都不起作用。有什么想法吗?

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);
}

1 个答案:

答案 0 :(得分:5)

以下是您的回答:

@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);
    }

希望这可行..:)