I have an
EditText and a
I want if an
EditText was empty when clicked on my
Button. I want to show message as a toast, like "please enter a number".
The cleanest way to do this is
TextUtils.isEmpty(editText.getText())The reason I say this is the cleanest way is because:
String. Which creates an object.
toString()creates an additional object which is not good. This method will also never return null in my experience.
lengthcheck out of that. If you look at the code for
TextUtils.isEmpty(), it basically checks if the
nulland length is zero.
Editableis an implementation of
If you want to check the length of the trimmed String. Then use:
TextUtils.isEmpty(editText.getText()) && TextUtils.getTrimmedLength(editText.getText()) == 0
If you want, you can create your own utility method to do this so you don't have to add such a long condition in your code repeatedly.
I would attached an
OnFocusChangeListener to your
EditText to check the change in value or a
TextWatcher or both depending on how critical your requirement is. If your field had focus and lost it, do your validation with the
OnFocusChangeListener, if your field has focus and the user is typing and delete the content or the content is too short, use
TextWatcher to let them know.