【问题标题】:Updating ListView using ArrayAdapter使用 ArrayAdapter 更新 ListView
【发布时间】:2013-10-16 14:43:12
【问题描述】:

我在 fragment 中使用了 ListView,但在更新 ListView 时遇到了问题。

这是我用于在ListView 上设置适配器的代码

    adapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1,
            ((TabNavigation)this.getActivity()).getItems());
    setListAdapter(adapter);

getItems() 是 String 数组的 getter,命名为 items:

items= new String[]{"item 1", "item 2", "item 3", "item 4", "item 5", "item 6"};

此时一切正常:我可以在我的列表中看到六项。

现在,如果我尝试以这种方式更新我的数组:

items[0]="injected item";

然后我通过我的适配器调用notifyDataSetChanged() 一切正常,因为我的列表中的项目正确更改,将字符串注入项目而不是项目1显示为第一个元素。 但是,如果我使用以下指令而不是该指令:

items= new String[]{"injected item", "item 2", "item 3", "item 4", "item 5", "item 6"};

然后我通过我的适配器调用notifyDataSetChanged(),列表没有更新。

我认为这取决于传递的参考价值。似乎适配器继续引用我第一次设置适配器时传递的数组副本。 事实上,如果我使用:

temp= new String[]{"injected item", "item 2", "item 3", "item 4", "item 5", "item 6"};      
System.arraycopy(temp, 0, items, 0, temp.length);

listView 已正确更新。但我必须使用与原始数组完全相同的长度。

所以实际的问题是:如果我需要更改列表中的项目数,如何更新ListView

【问题讨论】:

    标签: android listview android-listview android-arrayadapter


    【解决方案1】:

    您也可以使用 ListArray。适配器获取列表或数组对象以显示其项目。您可以为其设置任何数组或列表,并且在您需要更改项目的任何时候都可以更改它的数组,但如果您愿意,数组的长度可以保持不变更改您应该使用adapter.add("string"); 的数组项数。您也可以使用 listarray 而不是将数组传递给您的适配器,并且更改或添加也很容易。此代码可能对您有所帮助

    final ArrayList<String> list = new ArrayList<String>();
    for (int i = 0; i < values.length; ++i) {
        list.add(values[i]);
    }
    final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
    listview.setAdapter(adapter);
    

    【讨论】:

    • 只是一个问题@linux。为什么将 List 作为构造函数的最后一个参数传递,我收到以下警告 Type safety: The expression of type ArrayList needs unchecked conversion to conform to List&lt;String&gt; ??
    • 我认为是因为 ArrayList 扩展了 List.sorry 但我不确定
    • 现在可以了。我从另一个返回 ArrayList 而不是 ArrayList 的方法获取列表