我对在 Android 中编辑文本有疑问。
我有一个名为用户名的字段:
我希望每当有人写一个带空格的用户名时,例如“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);
}
}
}
但这并没有解决我的目的。我只想实现,每当有人使用带空格的用户名时,它应该接受空格,但在按下登录按钮时,它应该举杯
谢谢
最佳答案
只需检查您的编辑文本是否包含空格。
在按钮的 onClick()
事件中使用以下代码。
if (agrTextView.getText().toString().contains(" ")) {
agrTextView.setError("No Spaces Allowed");
Toast.makeText(MyActivity.this, "No Spaces Allowed", 5000).show();
}
关于Android 检查 EditText 中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14315633/