【问题标题】:Android: Open a custom pop up dialog from an options menuAndroid:从选项菜单打开自定义弹出对话框
【发布时间】:2011-11-07 04:58:52
【问题描述】:

是否可以有一个打开对话窗口的选项菜单项? 这是我得到的:

public class main extends Activity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int score;

    SharedPreferences stats = getSharedPreferences("TRHprefs", MODE_WORLD_READABLE);

    score = stats.getInt("score", 0);

    switch (item.getItemId()) {

        case R.id.score:

            Context mContext = getApplicationContext();
            Dialog dialog = new Dialog(mContext);

            dialog.setContentView(R.layout.options_menu);
            dialog.setTitle("Hero Stats");

            TextView b10 = (TextView) dialog.findViewById(R.id.tolevel);
            b10.setText("Score: " + score);

            dialog.setCancelable(true);
            dialog.show();

                            break;
        case R.id.options:     
            //Options

                            break;
        case R.id.quit: 
            //Quit
                            break;
    }
    return true;
}
}

当我选择分数选项按钮时,应用程序强制关闭。有什么想法吗?

【问题讨论】:

  • 能否请您提供logcat的输出,没有它只是猜测。

标签: android menu dialog popup options


【解决方案1】:

您应该包含 logcat 输出,以便更容易确定到底出了什么问题,但盯着代码我的期望是:

  1. 布局文件options_menu.xml 中存在错误,TextView b10 = (TextView) dialog.findViewById(R.id.tolevel); 行正在为b10 返回空值。如果发生这种情况,下一行将导致 NullPointerException 并且应用程序将强制关闭。
  2. Dialog dialog = new Dialog(mContext); 失败,因为您传递的是 ApplicationContext 而不是 Activity。尝试使用Dialog dialog = new Dialog(this);

【讨论】:

    猜你喜欢
    • 2011-09-30
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多