当我将计数器设置为减去并关闭应用程序时,我收到错误。我收到错误“无法为最终变量计数器赋值”。如果用户登录3次但没有成功退出应用程序。
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();
}
}
}
});
}
}
答案 0 :(得分: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 Event和How do I use onClickListener to count the number of times a button is pressed?可能有所帮助。
编辑:
你在其他部分所做的事情没有意义。您正在使用getText()从这些设置userText
和passText
的文本。然后,您将这些相同的值存储到user
和pass
。但是你没有在任何地方使用这些变量,并且当再次调用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();
}
}