Search code examples
androidandroid-edittext

Android EditText Space Validation


I have an Edittext in my android application. I don't want to allow user to enter first space character..but after entering other charecter user can enter space also..I used

    <EditText
    android:id="@+id/editText1_in_row"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="text" 
    android:digits="_,qwertzuiopasdfghjklyxcvbnm,QWERTYUIOPASDFGHJKLZXCVBNM,0123456789">

but in this case user can not enter space.

I have also used Text Watcher but I need not to allow user at the time of entering text as android:digits works.


Solution

  • final EditText editText = (EditText)findViewById(R.id.editText1_in_row);
    
    
            InputFilter filter = new InputFilter() { 
                boolean canEnterSpace = false;
    
                public CharSequence filter(CharSequence source, int start, int end,
                        Spanned dest, int dstart, int dend) {
    
                    if(editText.getText().toString().equals(""))
                    {
                        canEnterSpace = false;
                    }
    
                    StringBuilder builder = new StringBuilder();
    
                    for (int i = start; i < end; i++) { 
                        char currentChar = source.charAt(i);
    
                        if (Character.isLetterOrDigit(currentChar) || currentChar == '_') {
                            builder.append(currentChar);
                            canEnterSpace = true;
                        }
    
                        if(Character.isWhitespace(currentChar) && canEnterSpace) {
                            builder.append(currentChar);
                        }
    
    
                    }
                    return builder.toString();          
                }
    
            };
    
    
            editText.setFilters(new InputFilter[]{filter});
    

    and remove this property from your EditText

    android:digits="_,qwertzuiopasdfghjklyxcvbnm,QWERTYUIOPASDFGHJKLZXCVBNM,0123456789"
    

    This code works exactly according to your needs.