首页 > 解决方案 > 如何在for循环中增加edittexts的数量

问题描述

我有 8个EditText,我想检查这些EditTexts 是否为空。
这是我的代码:

if (edt1.getText().toString().equals("K")
      &&!edt2.getText().toString().equals("")
      &&!edt3.getText().toString().equals("")
      &&!edt4.getText().toString().equals("")
      &&!edt5.getText().toString().equals("")
      &&!edt6.getText().toString().equals("")
      &&!edt7.getText().toString().equals("")
      &&!edt8.getText().toString().equals("")){
    next();
}

这就是我要的:

int count=0;
for(int i=1;i<=8,i++){
    if(!edt.getText().toString().equals(""))//how can I increase the number of edt, if i=1, edt1 and if i=2, edt2... 
        count++;
}
if(count==8){
    next();
}

标签: javaandroidandroid-edittext

解决方案


在数组中逐行读取 EditText。那会简单得多。此外,您可以使用 String Utils http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html来检查空字符串,或者您可以使用默认的 null 和空字符串检查。

将 edt1,ed2,edt3 之类的引用放入一个数组并循环遍历它。那会奏效。

int count=0;
EditText edt[] = {edt1,edt2,edt3,edt4,edt5,edt6,edt7,edt8}
for(int i=0;i<=7,i++){
    if(edt[0].getText().toString().equals("K") || !edt[i].getText().toString().equals(""))
        count++;
}
if(count==8){
    next();
}

推荐阅读