Skip to content Skip to sidebar Skip to footer

Check If Edittext Has Specific Character

I searched a while but could not find how to check for a specific character in a string that was typed in an EditText?

Solution 1:

By using TextWatcher, you can achieve so.

        editText.addTextChangedListener(new TextWatcher() {
        publicvoidafterTextChanged(Editable s) {
        }

        publicvoidbeforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        publicvoidonTextChanged(CharSequence s, int start, int before,
                int count) {
            Log.i(TAG, "specific character = " + s.charAt(count-1));
        }
    });

Solution 2:

I am not sure when you would like to check whether a specific character is part of the text entered in the EditText. I assume, to check the existence of that character upon clicking the edit text field.

In your main activity, you would then add the following code. I assume that the view associated with your main activity contains an EditText with id id_edit_text.

publicclassMyActivityextendsActivity
{

     private EditText mEditText;

     ...

     @OverrideprotectedvoidonCreate(Bundle savedInstanceState)
     {
        ...
        mEditText = (EditText) this.findViewById (R.id.id_edit_text);
        mEditText.setOnClickListener (newView.OnClickListener ()
        {
            @OverridepublicvoidonClick(View view)
            {
                Stringcharacter="x";
                Stringtext= mEditText.getText ().toString ();
                if (text.contains (character)) {
                    Toast.makeText (MyActivity.this, "character found", Toast.LENGTH_SHORT).show ();
                }
            }
        });
        ...
    }
}

You can retrieve the current text of the EditText with mEditText.getText().toString(). And then, you can use that string and check if it contains the specific character.

Post a Comment for "Check If Edittext Has Specific Character"