我在Android中遇到有关“编辑文本”的问题。
我有一个名为Username的字段:
我希望有人写一个带有空格的用户名,例如“Gaurav Arora”。然后,应该在按登录按钮时举杯 toast 或出错。
我是以这种方式做的-我只是在文本观察器的帮助下停止了空格键的效果-
public static TextWatcher getNameTextWatcher(final TextView agrTextView) {
TextWatcher mTextWatcherName = new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
String result = agrTextView.getText().toString().replaceAll(" ", "");
if (!agrTextView.getText().toString().equals(result)) {
agrTextView.setText(result);
}
}
}
但这并没有解决我的目的。我只想实现只要该人使用带有空格的用户名,它就应该接受该空格,但是在按下登录按钮时,它应该引发 toast
谢谢
最佳答案
只需检查您的编辑文本是否包含空格。
在Button的onClick()
事件中使用以下代码。
if (agrTextView.getText().toString().contains(" ")) {
agrTextView.setError("No Spaces Allowed");
Toast.makeText(MyActivity.this, "No Spaces Allowed", 5000).show();
}