In EditText.addTextChangedListener() best way to refer to the string field value?

Viewed 39

In my Android application i need to check if the EditText field is not empty.

My code is working but i want to know the best way to refer to the string field value in my listener EditText.addTextChangedListener()

Here I just erased two @override function for convenience.

  1. Using EditText.getText().toString()
    edtGroupName.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String edtText = edtGroupName.getText().toString();
            btnUpdate.setEnabled( !TextUtils.isEmpty(edtText) );
        }
    });
  1. or using CharSequence.toString()
    edtGroupName.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String edtText = s.toString();
            btnUpdate.setEnabled( !TextUtils.isEmpty(edtText) );
        }
    });
1 Answers

You have to use second way instead of the first way and use afterTextChange instead of onTextChange .

If you want to check for every char that the user inserts or delete use this way, but if you want to check the edittext is empty or not to do some action like button click you can use

if(!TextUtils.isEmpty(edtGroupName.getText().toString())
{
   //button click or what you want
}
Related