If 语句显示特定的警报对话框

If statement to display specific alert dialog

当某个状态结束时,我会显示一个警告对话框。此对话框显示分数和高分。有没有办法在语句为真时显示特定的警报对话框?

 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 将包含第一组代码,仅显示分数和当前最高分。

我认为这对你有用:

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 输出添加到问题中,这样就可以识别任何其他错误(如果存在),那就太好了。