我在android中有5个EditTexts。我想知道我是否可以检查所有5个EditTexts是否为空。有什么办法可以做到吗?


当前回答

你也可以检查所有的EditText字符串在一个If条件:像这样

if (mString.matches("") || fString.matches("") || gender==null || docString.matches("") || dString.matches("")) {
                Toast.makeText(WriteActivity.this,"Data Incomplete", Toast.LENGTH_SHORT).show();
            }

其他回答

使用这段简短的代码,您可以删除字符串开头和结尾的空白。如果字符串是“”,则返回消息“error”,否则就是字符串

EditText user = findViewById(R.id.user); 
userString = user.getText().toString().trim(); 
if (userString.matches("")) {
    Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
    return; 
}else{
     Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}

以下几点对我来说很有用:

if(searchText.getText().toString().equals("")) 
    Log.d("MY_LOG", "Empty");

首先,我从EditText检索文本,然后将其转换为字符串,最后使用.equals方法将其与“”进行比较。

EditText edt=(EditText)findViewById(R.id.Edt);

String data=edt.getText().toString();

if(data=="" || data==null){

 Log.e("edit text is null?","yes");

}

else {

 Log.e("edit text is null?","no");

}

对所有五个编辑文本都这样做吗

其他答案是正确的,但要用一种简短的方式

if(editText.getText().toString().isEmpty()) {
     // editText is empty
} else {
     // editText is not empty
}

我更喜欢使用ButterKnife列表绑定,然后在列表上应用操作。例如,对于EditTexts,我在一个实用工具类中定义了以下自定义操作(在本例中是ButterKnifeActions)

public static <V extends View> boolean checkAll(List<V> views, ButterKnifeActions.Check<V> checker) {
    boolean hasProperty = true;
    for (int i = 0; i < views.size(); i++) {
        hasProperty = checker.checkViewProperty(views.get(i), i) && hasProperty;
    }
    return hasProperty;
}

public static <V extends View> boolean checkAny(List<V> views, ButterKnifeActions.Check<V> checker) {
    boolean hasProperty = false;
    for (int i = 0; i < views.size(); i++) {
        hasProperty = checker.checkViewProperty(views.get(i), i) || hasProperty;
    }
    return hasProperty;
}

public interface Check<V extends View> {
    boolean checkViewProperty(V view, int index);
}

public static final ButterKnifeActions.Check<EditText> EMPTY = new Check<EditText>() {
    @Override
    public boolean checkViewProperty(EditText view, int index) {
        return TextUtils.isEmpty(view.getText());
    }
};

在视图代码中,我将edittext绑定到一个列表,并在需要检查视图时应用操作。

@Bind({R.id.edit1, R.id.edit2, R.id.edit3, R.id.edit4, R.id.edit5}) List<EditView> edits;
...
if (ButterKnifeActions.checkAny(edits, ButterKnifeActions.EMPTY)) {
    Toast.makeText(getContext(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}

当然,这个模式可以扩展到检查任意数量的视图上的任何属性。唯一的缺点(如果你可以这么说的话)是视图的冗余。这意味着,要使用这些edittext,还必须将它们绑定到单个变量,以便可以通过名称引用它们,或者必须通过列表中的位置引用它们(editors .get(0)等)。就我个人而言,我只是将它们每个绑定两次,一次绑定到单个变量,一次绑定到列表,并使用任何合适的。