代码之家  ›  专栏  ›  技术社区  ›  jcw

将ArrayAdapter转换为List<String>

  •  1
  • jcw  · 技术社区  · 13 年前

    我有一个数组适配器(字符串),希望将其转换为 List<String> ,但在谷歌上搜索了一下并尝试了几次之后,我并没有更接近于弄清楚如何做到这一点。

    我已经尝试过以下内容;

    for(int i = 0; i < adapter./*what?*/; i++){
         //get each item and add it to the list
    }
    

    但这不起作用,因为似乎没有 adapter.length 或 adapter.size() 方法或变量。

    然后我尝试了这种for循环

    for (String s: adapter){
        //add s to the list
    }
    

    但适配器不能在foreach循环中使用。

    然后,我在谷歌上搜索了一个从适配器转换为列表的方法(在Arrays中),但一无所获。

    最好的方法是什么?这可能吗?

    2 回复  |  直到 13 年前
        1
  •  5
  •   M G    13 年前
    for(int i = 0; i < adapter.getCount(); i++){
         String str = (String)adapter.getItem(i);
    }
    
        2
  •  2
  •   DwB    8 年前

    试试这个

    // Note to the clown who attempted to edit this code.
    // this is an input parameter to this code.
    ArrayAdapter blammo; 
    List<String> kapow = new LinkedList<String>(); // ArrayList if you prefer.
    
    for (int index = 0; index < blammo.getCount(); ++index)
    {
        String value = (String)blammo.getItem(index);
        // Option 2: String value = (blammo.getItem(index)).toString();
        kapow.add(value);
    }
    
    // kapow is a List<String> that contains each element in the blammo ArrayAdapter.
    

    如果ArrayAdapter的元素不是字符串,请使用选项2。