gpt4 book ai didi

Android:从选项菜单打开自定义弹出对话框

转载 作者:行者123 更新时间:2023-11-30 04:33:43 25 4
gpt4 key购买 nike

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

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 输出,以便更容易确定到底出了什么问题,但盯着代码我的期望是:

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

关于Android:从选项菜单打开自定义弹出对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7250495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com