Search code examples
javaandroidandroid-edittexttextwatcherandroid-textwatcher

Auto remove leading space of any text of EditText?


Description

I am developing one app in which I have registration page. Inside registration page, I am doing registration by getting user's full name and mobile number.

Problem

While getting user's full name in edit text sometimes the user is pressing space bar before type his/her name.

I need you disable space-bar key before typing any text white user start typing his name I want to enable space-bar key. So that user can enter space between his/her Middle name and Last name.

What I have tried?

Answer

I am using text watcher in edit text.

user_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                inputLayoutname.setError(null);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                System.out.println(TAG+" s :"+s+ " start :"+start+" Before : "+before+" Count: "+count);
                String str = s.toString();

                if(str.length() > 0 && str.contains(" "))
                {
                    user_name.setError("Space is not allowed");
                    user_name.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {    

                if (user_name.getText().length() > 0)
                    inputLayoutname.setError(null);
            }
        });

What problem coming when I am implementing this code?

While user pressing firstly it automatically removing space suddenly. But when user trying to enter space between full name, it's again removing all text and showing empty edit text.

screen 1 while entering only space enter image description here

Here I am entering my Name and want to enter last name or middle name of space enter image description here

Here when I am entering space after my first name enter image description here


Solution

  • First, try to understand what he is trying to do

    He is trying to prevent user typing leading spaces and not after entering text.

    He doesn't want to trim username

    Update your code from

    if(str.length() > 0 && str.contains(" "))
                    {
                        user_name.setError("Space is not allowed");
                        user_name.setText("");
                    }
    

    to

    if(str.equals(" "))
                    {
                        user_name.setError("Leading Space is not allowed");
                        user_name.setText("");
                    }
    

    It will prevent user typing any space before name