1

我有一个数组适配器(字符串),并想将其转换为 a List<String>,但经过一番谷歌搜索和几次尝试后,我离弄清楚如何做到这一点还差得远。

我尝试了以下方法;

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

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

然后我尝试了这种类型的 for 循环

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

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

然后我在谷歌上搜索了一个从适配器转换为列表的方法(在数组中),但什么也没找到。

做这个的最好方式是什么?甚至可能吗?

4

2 回答 2

5
for(int i = 0; i < adapter.getCount(); i++){
     String str = (String)adapter.getItem(i);
}
于 2013-09-11T18:02:55.257 回答
2

尝试这个

// 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。

于 2013-09-11T18:06:39.163 回答