我在android中有5个EditTexts。我想知道我是否可以检查所有5个EditTexts是否为空。有什么办法可以做到吗?
当前回答
试试这个
TextUtils.isEmpty(editText.getText());
其他回答
我使用TextUtils来做这个:
if (TextUtils.isEmpty(UsernameInfo.getText())) {
validationError = true;
validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}
这个函数对我有用
private void checkForm() {
EditText[] allFields = {
field1_txt,
field2_txt,
field3_txt,
field4_txt
};
List < EditText > ErrorFields = new ArrayList < EditText > ();
for (EditText edit: allFields) {
if (TextUtils.isEmpty(edit.getText())) {
// EditText was empty
ErrorFields.add(edit); //add empty Edittext only in this ArayList
for (int i = 0; i < ErrorFields.size(); i++) {
EditText currentField = ErrorFields.get(i);
currentField.setError("this field required");
currentField.requestFocus();
}
}
}
}
以下几点对我来说很有用:
if(searchText.getText().toString().equals(""))
Log.d("MY_LOG", "Empty");
首先,我从EditText检索文本,然后将其转换为字符串,最后使用.equals方法将其与“”进行比较。
我通常按SBJ的建议去做,但反过来。我只是发现,通过检查阳性结果而不是双重否定,更容易理解我的代码。 您可能会询问如何检查空EdiTexts,但您真正想知道的是它是否有任何内容,而不是它是否为空。
像这样:
private boolean hasContent(EditText et) {
// Always assume false until proven otherwise
boolean bHasContent = false;
if (et.getText().toString().trim().length() > 0) {
// Got content
bHasContent = true;
}
return bHasContent;
}
作为SBJ,我更喜欢返回“没有内容”(或false)作为默认值,以避免异常,因为我取消了内容检查。这样,你就可以绝对确定,你的检查已经“批准”了一个true。
我还认为if调用它看起来也更简洁:
if (hasContent(myEditText)) {
// Act upon content
} else {
// Got no content!
}
这在很大程度上取决于个人偏好,但我发现这更容易阅读。:)
尝试使用If ELSE If条件。您可以轻松地验证editText字段。
if(TextUtils.isEmpty(username)) {
userNameView.setError("User Name Is Essential");
return;
} else if(TextUtils.isEmpty(phone)) {
phoneView.setError("Please Enter Your Phone Number");
return;
}
推荐文章
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 如何在android中复制一个文件?
- adb找不到我的设备/手机(MacOS X)
- 如何在新的材质主题中改变背面箭头的颜色?