问题描述
我使用的是的ListView
A 片段内
,但我无法更新的ListView。
I'm using a ListView
inside a fragment
but I'm having trouble updating the ListView.
这是我使用的设置我的的ListView适配器的code
This is the code that I use for setting the adapter on my ListView
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1,
((TabNavigation)this.getActivity()).getItems());
setListAdapter(adapter);
其中, getItems()
是字符串数组一个getter,命名项:
where getItems()
is a getter for the String array, named items:
items= new String[]{"item 1", "item 2", "item 3", "item 4", "item 5", "item 6"};
此时一切工作好。我可以在列表中看到的六个项目
At this point all works good: I can see in my list the six item.
现在,如果我尝试更新我这样数组:
Now, if I try to update my array in this way:
items[0]="injected item";
和比我称之为 notifyDataSetChanged()
在我的适配器的所有作品finem,因为在我的名单更改的项目正确,显示作为第一要素的字符串注入的项目,而不是项目1。
但是,如果不是该指令我使用以下命令:
and than I call notifyDataSetChanged()
over my adapter all works finem, because the item in my list change correctly, showing as first element the String injected item instead of item 1.But, if instead of that instruction I use the following:
items= new String[]{"injected item", "item 2", "item 3", "item 4", "item 5", "item 6"};
和比我称之为 notifyDataSetChanged()
在我的适配器,列表不会更新。
and than I call the notifyDataSetChanged()
over my adapter, the list is not update.
我觉得这取决于价值参考通道。好像适配器继续引用数组传递的副本时,我设置好的适配器第一次。
事实上,如果我使用:
I think this depends on the passage of value for reference. Seems like the adapter continues to refer to the copy of array passed when I setted the adapter first time.In fact if I use :
temp= new String[]{"injected item", "item 2", "item 3", "item 4", "item 5", "item 6"};
System.arraycopy(temp, 0, items, 0, temp.length);
在ListView是更新正确。但我必须使用完全相同的原始数组相同lenght。
the listView is update correctly. But I must use exactly the same lenght of the original array.
所以实际的问题是:我怎么可以更新的ListView
如果我需要更改列表内的项目数
So the actual question is: how can I update the ListView
if I need to change the number of the items inside the list?
推荐答案
您可以使用ListArray too.adapter得到一个列表或数组对象为显示其items.you可以在任何数组或列表设置为它,随时随地你需要更改项目你可以改变它阵列,但阵列具有恒定的lenght如果你想改变数组的项目,你应该使用的数量 adapter.add(字符串);
。你可以使用listarray而不是通过数组适配器太和更改或添加也很简单。这code可以帮助你。
you can use ListArray too.adapter get a list or array object for display its items.you can set any array or list to it and anytime you need change items you can change it array but array have lenght of constant if you want change number of items of array you should use adapter.add("string");
.you can use listarray instead of pass array to your adapter too and change or add is easy too. this code may help you
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);
这篇关于更新使用ArrayAdapter的ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!