Check if EditText has specific character

*爱你&永不变心* 提交于 2020-01-06 03:37:07

问题


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.



来源:https://stackoverflow.com/questions/26831163/check-if-edittext-has-specific-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!