Java 无法验证AlertDialog的setPositiveButton下的EditText
我有一个Java 无法验证AlertDialog的setPositiveButton下的EditText,java,android,android-alertdialog,Java,Android,Android Alertdialog,我有一个AlertDialog,它需要用户输入密码才能执行特定操作。但是,当我尝试将密码与字符串进行比较以验证密码是否正确时,代码不会执行任何操作,也不会显示任何错误。当我尝试比较字符串的长度时,代码工作正常,并在该条件下执行代码,如果EditText为空,它还会提示用户 我希望代码执行的是:if(password==“password”| |“otherpassword”){execute code} 下面是我的方法,它通过测量密码的长度来工作: public void redeem(View
AlertDialog
,它需要用户输入密码才能执行特定操作。但是,当我尝试将密码与字符串进行比较以验证密码是否正确时,代码不会执行任何操作,也不会显示任何错误。当我尝试比较字符串的长度时,代码工作正常,并在该条件下执行代码,如果EditText
为空,它还会提示用户
我希望代码执行的是:if(password==“password”| |“otherpassword”){execute code}
下面是我的方法,它通过测量密码的长度来工作:
public void redeem(View view) {
final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Password")
.setView(taskEditText)
.setPositiveButton("Redeem", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String password = taskEditText.getText().toString();
if (password.length() == 4) {
// Execute piece of code
} else if (password.isEmpty() == true) {
Toast.makeText(PostDetailActivity.this, "The password cannot be empty", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
您可以使用
password.equals(“密码”)
在您的情况下,它将是:
if(password.equals(“password”)| password.equals(“someOtherPassword”)){
}
此外,为了避免/确保结果区分大小写,您可以将boolean
参数传递给equals()
函数。就像“password”。等于(“password”,true)
那么它将返回false作为密码=密码
。类似地,您可以使用“password”.equals(“password”,false)
,在这种情况下password==password
[忽略大写或小写字符。]
另外,在
else if
分支中,不需要执行else if(password.isEmpty()==true)
else if(password.isEmpty())
单独完成任务。这是什么>>final EditText taskEditText=new EditText(此)代码>?这是来自对话框的Edittext吗?您在哪里添加?代码是以编程方式添加Edittext
。您面临的问题是什么?