【问题标题】:Converting an ArrayAdapter to a List<String>将 ArrayAdapter 转换为 List<String>
【发布时间】:2013-09-11 17:57:42
【问题描述】:

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

我尝试了以下方法;

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 循环中使用。

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

最好的方法是什么?有没有可能?

【问题讨论】:

标签: android arraylist android-arrayadapter


【解决方案1】:
for(int i = 0; i < adapter.getCount(); i++){
     String str = (String)adapter.getItem(i);
}

【讨论】:

  • 这看起来正是我想要的,谢谢。我讨厌谷歌不能使长度名称统一的事实。他们调用size()length 方法会不会太难?
  • 语义上,getCount() 更合适,因为它应该告知适配器将创建的视图数量,这与 ArrayList 或包含数据的数组不同,它确实具有大小:它包含的元素数量。 ArrayAdapter 不一定包含数据,因此它没有大小。
  • 另请注意,ArrayAdapter 类是通用的,因此如果您使用new ArrayAdapter(...)&lt;String&gt;,您可以避免转换 getItem() 返回的值。
【解决方案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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2021-05-18
    • 2013-08-26
    相关资源
    最近更新 更多