Check if EditText has specific character

2019-08-02 15:43发布

问题:

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

回答1:

By using TextWatcher, you can achieve so.

        editText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

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


回答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.

public class MyActivity extends Activity
{

     private EditText mEditText;

     ...

     @Override
     protected void onCreate (Bundle savedInstanceState)
     {
        ...
        mEditText = (EditText) this.findViewById (R.id.id_edit_text);
        mEditText.setOnClickListener (new View.OnClickListener ()
        {
            @Override
            public void onClick (View view)
            {
                String character = "x";
                String text = 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.