I have several
EditText
boolean filledName, filledAddress = false; //These variables will determine if my fields are empty or not
EditText name, address;
Button btnEnter;
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
...
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);
}
}