Android check spaces in EditText

2019-06-22 01:22发布

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

6条回答
时光不老,我们不散
2楼-- · 2019-06-22 02:00

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();
 }
查看更多
乱世女痞
3楼-- · 2019-06-22 02:01

use trim() method to remove all spaces and then check for empty

if ( !edtText.getText().toString().trim().isEmpty()) {
  //the EditText is not Empty
}
查看更多
放荡不羁爱自由
4楼-- · 2019-06-22 02:04
 String question = txtNote.getText().toString();
 if(question.trim().length() > 0){
    Log.i("LOG", "Has value");
 }else{
    Log.i("LOG", "don't has value");
   }
查看更多
Rolldiameter
5楼-- · 2019-06-22 02:04

Also you can block entering space bar in username, or can give toast or snack on entering space in username .

Can refer this link might be helpful for you Block entering space in edittext.

Let me know if any concern.

查看更多
We Are One
6楼-- · 2019-06-22 02:06

Simply do this:

TextView.getText().toString().contains(" ");
查看更多
等我变得足够好
7楼-- · 2019-06-22 02:17

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();
        }
    });
查看更多
登录 后发表回答