【问题标题】:If statement to display specific alert dialogIf 语句显示特定的警报对话框
【发布时间】:2016-05-01 15:55:47
【问题描述】:

当状态完成时,我会显示一个警报对话框。此对话框显示分数和高分。有没有办法在陈述为真时显示特定的警报对话框?

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Score: " + Score + " High Score: " + highScore)
            .setPositiveButton(R.string.returnString, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(getActivity(), GameState.class);
                    startActivity(intent);
                }
            });
    return builder.create();

我在下面尝试了这个,但不起作用,只是让应用程序崩溃。

     if(Score > highScore) {
        builder.setMessage("You have set a new high score: " + highScore)
                .setPositiveButton(R.string.returnString, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(getActivity(),GameState.class);
                        startActivity(intent);
                    }
                });

然后 else 将包含第一组代码,仅显示分数和当前高分。

【问题讨论】:

  • Score是什么对象?崩溃的信息是什么?
  • @Martin 他们都是整数
  • 即使是 Integer 类也需要一个方法 ( ´intValue()´ ) 才能获得“真正的”int。
  • 您能在此处添加 logcat 崩溃/堆栈跟踪消息吗?

标签: java android android-alertdialog


【解决方案1】:

我认为这应该适合你:

String message = "Score: " + Score + " High Score: " + highScore;
if(Score > highScore) {
    message = "You have set a new high score: " + highScore;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(message)
        .setPositiveButton(R.string.returnString, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(getActivity(), GameState.class);
                startActivity(intent);
            }
        });
return builder.create();

这将解决条件消息显示问题。但是,如果您将 logcat 输出添加到问题中,这样也可以识别任何其他错误(如果存在),那将是非常棒的。

【讨论】:

  • 这就是我想要的。我不敢相信我没有想到这一点。这完美地工作。非常感谢。
  • 很高兴能帮上忙 :)
猜你喜欢
  • 2022-11-07
  • 1970-01-01
  • 2023-03-13
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 2011-06-17
相关资源
最近更新 更多