Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android check spaces in EditText

I have a problem regarding Edit Text in Android.

I have a field named Username :

I want that whenever someone writes a username with a space e.g "Gaurav Arora". Then it should raise a toast or error on the login button press.

I did in this way - I simply stopped the effect of space bar with the help of a text watcher as-

public static TextWatcher getNameTextWatcher(final TextView agrTextView) {
        TextWatcher mTextWatcherName = new TextWatcher() {
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
            }

            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {
            }

            public void afterTextChanged(Editable arg0) {

                String result = agrTextView.getText().toString().replaceAll(" ", "");
                if (!agrTextView.getText().toString().equals(result)) {
                    agrTextView.setText(result);
                }

}
}

But this has not solved my purpose. I just want to implement whenever the person uses a username with space it should accept the space but on the press of login button it should raise a toast

Thanks

like image 770
Gaurav Arora Avatar asked Jan 14 '13 09:01

Gaurav Arora


3 Answers

Just check if your edit text contains blank space or not.

Use the following code in the onClick() event of the Button.

 if (agrTextView.getText().toString().contains(" ")) {
     agrTextView.setError("No Spaces Allowed");
     Toast.makeText(MyActivity.this, "No Spaces Allowed", 5000).show();
 }
like image 188
Sahil Mahajan Mj Avatar answered Oct 22 '22 03:10

Sahil Mahajan Mj


Try this..

     btnLogin.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String result = agrTextView.getText().toString();
             if(result.contains ("\\s"))
               Toast.makeText(getApplicationContext(), "Space ", Toast.LENGTH_LONG).show();
        }
    });
like image 23
Deepzz Avatar answered Oct 22 '22 03:10

Deepzz


Simply do this:

TextView.getText().toString().contains(" ");
like image 4
user3464252 Avatar answered Oct 22 '22 01:10

user3464252