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()