检查的EditText有特定的字符(Check if EditText has specific c

2019-10-21 06:26发布

我搜索了一会儿,但无法找到如何检查字符串中的特定字符在一个EditText类型?

Answer 1:

通过使用TextWatcher,可以实现左右。

        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));
        }
    });


Answer 2:

我不知道,当你想检查特定的字符是否在EditText上输入的文本的一部分。 我认为,在点击编辑文本字段,检查角色的存在。

在您的主要活动,那么您需要添加以下代码。 我假设你的主要活动相关的视图包含ID为一个EditText 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 ();
                }
            }
        });
        ...
    }
}

你可以检索的EditText与当前文本mEditText.getText().toString() 。 然后,你可以使用该字符串并检查它是否包含特定字符。



文章来源: Check if EditText has specific character