循环通过List android

时间:2013-09-01 07:20:49

标签: java android list arraylist

我有以下方法:

 public List<String> getAllValue(){
       List<String> list = new ArrayList<String>();
       if(pref.getString(KEY_NUMBER1 , "").length()>2)
           list.add(pref.getString(KEY_NUMBER1 , ""));
       if(pref.getString(KEY_NUMBER2 , "").length()>2)
           list.add(pref.getString(KEY_NUMBER2 , ""));
       if(pref.getString(KEY_NUMBER3 , "").length()>2)
           list.add(pref.getString(KEY_NUMBER3 , ""));
       if(pref.getString(KEY_NUMBER4 , "").length()>2)
           list.add(pref.getString(KEY_NUMBER4 , ""));
       if(pref.getString(KEY_NUMBER5 , "").length()>2)
           list.add(pref.getString(KEY_NUMBER5 , ""));

       return list;
   }

我现在需要做的是将这些数字(例如KEY_NUMBER1)分配给以下editTexts

EditText phoneNumber1, phoneNumber2, phoneNumber3, phoneNumber4, phoneNumber5;

刚开始使用Lists时,我很难找到一种循环方式并为这些editTexts赋值,比如

phoneNumber1.setText(KEY_NUMBER1);
phoneNumber2.setText(KEY_NUMBER2);
phoneNumber3.setText(KEY_NUMBER3);

3 个答案:

答案 0 :(得分:26)

假设list是您的List<String>从该功能返回的。你可以像下面这样循环:

for (int i=0; i<list.size(); i++) {
    System.out.println(list.get(i));
}

为了分配EditText,你可以使用索引,如果你是项目的数量并且它是固定的(这里似乎是5):

phoneNumber1.setText(list.get(0));
phoneNumber2.setText(list.get(1));
//so on ...

答案 1 :(得分:1)

科特林:

val numbers = listOf("one", "two", "three", "four")
for (item in numbers) {
    println(item)
}

val numbers = listOf("one", "two", "three", "four")
val numbersIterator = numbers.iterator()
while (numbersIterator.hasNext()) {
    println(numbersIterator.next())
}

答案 2 :(得分:0)

for (E element : list) {
    . . .
}