I have read this question How to disable Button if EditText is empty ?
But there it is only 1 EditText
field. What is an elegant solution to use a TextWatcher to enable or disable a Button
if both of two EditText
fields are either empty or contain text?
This is my approach and it works, but it makes no use of any of the arguments passed in onTextChanged
. What do you think?
public class MainActivity extends AppCompatActivity implements TextWatcher {
private EditText editTextUsername;
private EditText editTextPassword;
private Button buttonConfirm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUsername = findViewById(R.id.edit_text);
editTextPassword = findViewById(R.id.edit_password);
buttonConfirm = findViewById(R.id.button_confirm);
editTextUsername.addTextChangedListener(this);
editTextPassword.addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String usernameInput = editTextUsername.getText().toString().trim();
String passwordInput = editTextPassword.getText().toString().trim();
buttonConfirm.setEnabled(!usernameInput.isEmpty() && !passwordInput.isEmpty());
}
@Override
public void afterTextChanged(Editable s) {
}
}