我在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();
            }

其他回答

这里的派对已经晚了,但我只需要添加Android自己的TextUtils。isEmpty (CharSequence进行str)

如果字符串为null或0-length则返回true

所以如果你把你的五个edittext放在一个列表中,完整的代码将是:

for(EditText edit : editTextList){
    if(TextUtils.isEmpty(edit.getText()){
        // EditText was empty
        // Do something fancy
    }
}
if(TextUtils.isEmpty(textA.getText())){
            showToast(it's Null");
        }

你可以使用TextUtils。isEmpty就像我的例子! 祝你好运

我更喜欢使用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)等)。就我个人而言,我只是将它们每个绑定两次,一次绑定到单个变量,一次绑定到列表,并使用任何合适的。

EditText txtUserID = (EditText) findViewById(R.id.txtUserID);

String UserID = txtUserID.getText().toString();

if (UserID.equals("")) 

{
    Log.d("value","null");
}

您将在LogCat....中看到该消息

我使用这个方法,使用trim()来避免空格:

EditText myEditText = (EditText) findViewById(R.id.editUsername);
if ("".equals(myEditText.getText().toString().trim()) {
    Toast.makeText(this, "You did not enter a value!", Toast.LENGTH_LONG).show();
    return;
}

一个例子,如果你有几个EditText´

if (("".equals(edtUser.getText().toString().trim()) || "".equals(edtPassword.getText().toString().trim()))){
        Toast.makeText(this, "a value is missing!", Toast.LENGTH_LONG).show();
        return;
}