局部变量在OnClickListener中不可见

时间:2013-06-05 08:41:56

标签: java android

我正在开发Android应用程序,但我遇到了问题:

我有这个方法:

// User has introduced an incorrect password.
private void invalidPassword()
{
    // R.id.string value for alert dialog title.
    int dialogTitle = 0;
    // R.id.string value for alert dialog message.
    int dialogMessage = 0;
    boolean hasReachedMaxAttempts;

    clearWidgets();
    numIntents++;
    hasReachedMaxAttempts = (numIntents > maxNumIntents);

    // Max attempts reached
    if (hasReachedMaxAttempts)
    {
        dialogTitle = R.string.dialog_title_error;
        dialogMessage = R.string.dialog_message_max_attempts_reached;
    }
    else
    {
        dialogTitle = R.string.dialog_title_error;
        dialogMessage = R.string.dialog_message_incorrect_password;
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(dialogMessage)
           .setTitle(dialogTitle);
    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
    {
           public void onClick(DialogInterface dialog, int id)
           {
               // TODO: User clicked OK button
               if (hasReachedMaxAttempts)
               {
               }
               else
               {
               }
           }
       });

    AlertDialog dialog = builder.create();
    dialog.show();
}

如何在boolean hasReachedMaxAttempts;内显示onClick

3 个答案:

答案 0 :(得分:4)

你需要该变量为最终变量;

final boolean hasReachedMaxAttemptsFinal = hasReachedMaxAttempts;
AlertDialog.Builder builder = new AlertDialog.Builder(this);

 if (hasReachedMaxAttemptsFinal)

答案 1 :(得分:2)

final boolean hasReachedMaxAttempts;声明您的class level变量,它应该完成任务

答案 2 :(得分:2)

它是可见的,但需要设置为final

final boolean hasReachedMaxAttempts = (numIntents > maxNumIntents);