Palang Palang - 6 months ago 27
Android Question

How to check EditText isEmpty in Android

I want to create a login page, I used

EditText
to insert user info. I want to check
EditText
to see if it is Empty Invisible login Button, when inserted any character with user visible Login Button.

I tried the code shown below, but it did not not work for me :

//Show Login Button
String login_phoneString = login_PhoneText.getText().toString().trim();
if (login_phoneString.isEmpty()) {
login_image.setVisibility(View.INVISIBLE);
} else {
login_image.setVisibility(View.VISIBLE);
}


When
EditText
is empty, the button is invisible, and when set character in
EditText
again the login button is not shown.

How can I fix this problem ?

Answer

You want to show/hide the Login button base on the text of EditText so you need to listen for changing in EditText by use TextWatcher.
Use this code inside onCreate() method

login_PhoneText.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            String login_phoneString = login_PhoneText.getText().toString().trim();
            if (login_phoneString.isEmpty()) {
                login_image.setVisibility(View.INVISIBLE);
            } else {
                login_image.setVisibility(View.VISIBLE);
            }
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        public void onTextChanged(CharSequence s, int start, int before, int count) {}
});