如何检查在编辑文本中输入的文本中的初始空格 android

How to check for initial spaces in the text entered in edit text android

我在 android 应用程序中验证编辑文本时遇到问题。我尝试了很多方法,其中 none 适合我的场景。当用户尝试保存 post 时,在编辑文本字段中仅输入 spaces,我需要弹出一条错误消息。但是我能够检查用户只输入 spaces.

的条件

我用过以下方法:

if(subjectText.isEmpty() || detailsText.isEmpty() || subjectText.equals(" ") || detailsText.equals(" ")){

// perform operation.

}

此处 .equals(" ") 方法仅检查一个 space。如果用户条目是 " " 之类的东西而不是文本,我如何检查告诉用户没有文本。请任何人告诉我。欢迎所有建议。

我也试过 .contains(" ") 方法,这个方法解决了问题,但即使文本之间有 space,它也会弹出不应该发生的错误。如果用户输入是 "how are you".contains(" ") 方法会报错。

我该如何解决这个问题。请帮我解决这个问题。

您可以使用 startsWith(" ") 检测字符串开头的空格。

编辑:

可能是这样的

if(subjectText.isEmpty() || detailsText.isEmpty() || subjectText.startsWith(" ") || detailsText.startsWith(" ")){

// perform operation.

}

试试这个,删除您从 EditText 中输入的所有空格

if(subjectText.trim().length()<1){
   //perform action
}

为此进行正则表达式检查。像这样检查 whitespaces;

if(... || subjectText.matches("^\s*$") || ... }

对于白色space你也可以

subjectText.trim().lenght==0

试试这个:

final String subjectText = "  foo   ";
if (subjectText.replaceFirst("\s+$", "").length() == 0) {

// perform operation.

}

代码来自 here