简体   繁体   English

局部变量在OnClickListener中不可见

[英]Local variable not visible inside OnClickListener

I'm developing an Android application and I have a problem: 我正在开发一个Android应用程序,我有一个问题:

I have this method: 我有这个方法:

// 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();
}

How can I make visible boolean hasReachedMaxAttempts; 如何使可见的boolean hasReachedMaxAttempts; inside onClick ? onClick里面?

you need that variable to be final; 你需要那个变量是最终的;

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

 if (hasReachedMaxAttemptsFinal)

Declare your final boolean hasReachedMaxAttempts; 声明你的final boolean hasReachedMaxAttempts; variable at class level and it should get the task done class level变量,它应该完成任务

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

final boolean hasReachedMaxAttempts = (numIntents > maxNumIntents);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM