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.