2016-12-15 52 views
-3

当设置计数器以减去并关闭应用程序时,出现错误。我收到一个错误“无法将值赋给最终变量计数器”。如果用户登录3次而没有成功退出应用程序。如何在android studio中添加计数器以退出应用程序

 final int counter = 3; 

     //Set the OKButton to accept onClick 
     OKButton.setOnClickListener(new View.OnClickListener() { 
      @Override 

      //once onClick is initalized it takes user to page menu 
      public void onClick(View v) { 

       //display text that was inputed for userText and passText 
       user = userText.getText().toString(); 
       pass = passText.getText().toString(); 

       //create if loop which checks if user and pass equals the credentials 
       if (user.equals("pshivam") && pass.equals("Bway.857661")) { 

        //display toast access welcome 
        String welcome = "Access Granted."; 

        //Create a Toast to display the welcome string in the MainActivity. 
        Toast.makeText(MainActivity.this, welcome, Toast.LENGTH_SHORT).show(); 
        setContentView(R.layout.account_main); 
       } 
       //create else if loop which checks if user or pass does not equals the credentials 
       else if (!user.equals("pshivam") || !pass.equals("Bway.857661")){ 

        //displays previous entry 
        userText.setText(user); 
        passText.setText(pass); 

        //allows user to re-enter credentials. 
        user = userText.getText().toString(); 
        pass = passText.getText().toString(); 


        //display toast access fail 
        String fail = "Access Denied! Please Try again."; 
        //Create a Toast to display the fail string in the MainActivity. 
        Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show(); 
        counter--; 
        if(counter == 0){ 
         finish(); 
        } 
       } 
      } 
     }); 
    } 
} 
+2

你不能改变最终变量的值 – uptoNoGood

+0

我该如何改变它?使用一个普通的int? –

+0

检查我的答案 – uptoNoGood

回答

0

做这样的事情:

OKButton.setOnClickListener(new View.OnClickListener() { 
      int counter = 3; 
      @Override 
      //once onClick is initalized it takes user to page menu 
      public void onClick(View v) { 

您也可以从里面onClick调用一个函数,它会递减变量,或使用你的类中声明静态字段

How to increment a Counter inside an OnClick View EventHow do I use onClickListener to count the number of times a button is pressed?可能会有所帮助。

编辑:

你在做的其他部分没有任何意义。你正在设置文本userTextpassText,你刚刚从这些使用getText()。然后,您将这些相同的值存储到userpass。但是,当您再次调用onClick时,您并未在任何地方使用这些变量,并且它们会得到新值。为什么不保持简单:

   else { 

        //display toast access fail 
        String fail = "Access Denied! Please Try again."; 
        //Create a Toast to display the fail string in the MainActivity. 
        Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show(); 
        counter--; 
        if(counter == 0){ 
         finish(); 
        } 
       } 
相关问题