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


当前回答

我更喜欢使用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为空,试试另一种简单的方法:

String star = editText.getText().toString();

if (star.equalsIgnoreCase("")) {
  Toast.makeText(getApplicationContext(), "Please Set start no", Toast.LENGTH_LONG).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
    }
}
private boolean hasContent(EditText et) {
       return (et.getText().toString().trim().length() > 0);
}

试试这个

TextUtils.isEmpty(editText.getText());

我想做一些类似的事情。但是从edit text中获取文本值并像(str=="")那样进行比较对我来说并不管用。所以更好的选择是:

EditText eText = (EditText) findViewById(R.id.etext);

if (etext.getText().length() == 0)
{//do what you want }

效果很好。