在启用按钮之前验证所有 EditText 字段?

512*_*bee 4 validation android android-edittext

我有几个EditText字段(例如NameAddress等),我想验证/检查它们是否为。如果所有这些都已填满,我想将Enter按钮设置为enabled。如果任何一个字段都是空的,我想禁用Enter 按钮。

我在下面编写了我的代码,但即使我的所有字段都已填写,我的按钮仍未启用。我正在使用一堆布尔变量来确定是否满足条件。

我不确定我哪里出错了,因为我的应用程序运行正常,但不是我想要的结果,如果我的一个或所有字段为空,则会禁用 Enter 按钮。

我的变量:

boolean filledName, filledAddress = false; //These variables will determine if my fields are empty or not
EditText  name, address;
Button btnEnter;
Run Code Online (Sandbox Code Playgroud)

我的 onCreate:

protected void onCreate(Bundle savedInstanceState) {

...
//Get views from layout xml via IDs
name = (EditText) findViewById(R.id.name);
address = (EditText) findViewById(R.id.address);
btnEnter = (Button) findViewById(R.id.btnEnter);

btnEnter.setEnabled(false); //initialize the Enter button to be disabled on Activity creation

...
Run Code Online (Sandbox Code Playgroud)

我在 onCreate 中添加文本更改侦听器:

name.addTextChangedListener (new TextWatcher() {
   @Override
   public void onTextChanged(CharSequence s, int i, int i1, int i2){
        if (!(name.toString().trim().isEmpty()))
           filledName = true;      //if name field is NOT empty, filledName value is true
   }
   ....
   //other implemented abstract codes here
});

address.addTextChangedListener (new TextWatcher() {
   @Override
   public void onTextChanged(CharSequence s, int i, int i1, int i2){
        if (!(address.toString().trim().isEmpty()))
           filledAddress = true;     //if address field is NOT empty, filledAddress value is true
   }
   ....
   //other implemented abstract codes here
});

//This should set the Enter button to enabled once all the boolean conditions are met
//but for some reason it's not working
if (nameFilled == true && addressFilled == true)
   btnEnter.setEnabled(true);

} //end of onCreate()
Run Code Online (Sandbox Code Playgroud)

Jua*_*ler 6

我不建议您保存布尔值,因为您还必须false在字段再次为空时将其更改为。

我认为这样做更好:

protected void onCreate(Bundle savedInstanceState) {
    //......

    name.addTextChangedListener (new TextWatcher() {
       @Override
       public void onTextChanged(CharSequence s, int i, int i1, int i2){
            checkRequiredFields();
       }
    });

    address.addTextChangedListener (new TextWatcher() {
       @Override
       public void onTextChanged(CharSequence s, int i, int i1, int i2){
            checkRequiredFields();
       }
    });

    //......
}

private void checkRequiredFields() {
    if (!name.getText().toString().isEmpty() && !address.getText().toString().isEmpty()) {
       btnEnter.setEnabled(true);
    } else {
       btnEnter.setEnabled(false);
    }
}
Run Code Online (Sandbox Code Playgroud)