2011-08-30 41 views
1

弹出对话框是否有可能有打开一个对话框窗口的选项菜单项? 这里就是我的了:安卓:打开自定义从选项菜单

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

当我选择了比分选项按钮,该应用程序强制关闭。有任何想法吗?

+0

可否请您提供logcat的输出,它只是猜测,没有它。 – EpicOfChaos

回答

1

您应该包括logcat的输出,使其更容易确定究竟是哪里错了,但在代码盯着我的期望是,要么:

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