Ihor Ihor - 3 months ago 10
Java Question

Checking if 2 (or more) EditTexts are empty

Have 2 EditTexts (accName and accMoney) to be checked not to be empty in order to enable Button (btnCrAcc).

Tried to do like the code below. But it's actually not checking the way I'd like to. When I change the accMoney field, it's checking both EditTexts (but after that I can change accName to "" and the Button will be enabled anyway.

I think that one possible solution is to set the

addTextChangedListener
for both 2 fields, but it'll consume more memory? (Tell me: is that a good option?)

Or I'd be really grateful if someone tells me how to do that correctly

I have this code:

protected void onCreate(Bundle savedInstanceState) {
//..
accName = (EditText) findViewById(R.id.txtName);
accMoney = (EditText) findViewById(R.id.txtMoney);
accDescr = (EditText) findViewById(R.id.txtDescr);
accsListView = (ListView) findViewById(R.id.listView);
//..
final Button btnCrAcc = (Button) findViewById(R.id.btnCreateAccount);

accMoney.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}

@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

btnCrAcc.setEnabled(!accName.getText().toString().trim().isEmpty());
btnCrAcc.setEnabled(!accMoney.getText().toString().trim().isEmpty()); // check this
}

@Override
public void afterTextChanged(Editable editable) {

}
});
}

Answer

Try this one:

TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            btnCrAcc.setEnabled(!accName.getText().toString().trim().isEmpty() && !accMoney.getText().toString().trim().isEmpty());
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

accMoney.addTextChangedListener(watcher);
accName.addTextChangedListener(watcher;