I have several EditText
fields (such as Name, Address, etc.) that I want to validate/check if they are empty or not. If all of them are filled, I want to set my Enter button to enabled. If even any one of the fields are empty, I want to disable the Enter button.
I have written my code below but my button is not being enabled even after all my fields are already filled. I'm using a bunch of boolean variables to determine whether the condition is met.
I'm not sure where I went wrong since my app runs ok but not the desired results that I want which is disabling the Enter button if one or all of my fields are empty.
My variables:
boolean filledName, filledAddress = false; //These variables will determine if my fields are empty or not
EditText name, address;
Button btnEnter;
My 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
...
And my Add Text Changed Listeners inside my 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()
I do not recommend you to save a boolean, because you also have to change it to false
when the field is empty again.
I think that is better to do this:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With