Auto remove leading space of any text of EditText?

后端 未结 4 1355
灰色年华
灰色年华 2021-01-16 07:21

Description

I am developing one app in which I have registration page. Inside registration page, I am doing registration by getting user\'s full nam

相关标签:
4条回答
  • 2021-01-16 07:50

    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

    0 讨论(0)
  • 2021-01-16 07:57

    Use trim() method to remove the extra space

    user_name.getText().toString().trim().

    And Remove

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

    from your onTextChanged

    To prevent user from entering space add this on your onTextChanged

    if(str.equals(" "))
                    {
                        user_name.setError("Leading Space is not allowed");
                        user_name.setText("");
                    }
    
    0 讨论(0)
  • 2021-01-16 07:59

    use this trim() method to remove the space like this..

    String str = s.toString().trim();
    
    0 讨论(0)
  • 2021-01-16 08:00

    Try this, check if start == 0, it will not allow user to add spaces before name

    @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(start == 0 && s.toString().contains(" ")){
                    user_name.setText("");
                }
            }
    
    0 讨论(0)
提交回复
热议问题