【发布时间】: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