我有安卓应用程序,它使用带有自定义对象适配器的列表视图。
on创建活动 如果对象列表可用,我用以前的对象填充适配器,并进行异步调用以获取新对象并填充适配器。
再次填充适配器时,将删除旧的元素列表并添加新元素。我没有使用通知数据集更改()。
private CustomAdapter listAdapter;
private GridView gridView;
// this is onCreateView of fragment if i find old list in singleton i populate list and it shows on screen
function onCreateView()
{
...
...
listAdapter = new CustomAdapter(getActivity(),
CounterSingleton.getInstance(getActivity())
.getObjects());
gridView.setAdapter(listAdapter);
....
...
new AsnycTask().execute();
}
class AsnycTask
{
// fetch new list and replace old list shown
List<Objects> newList = fetchNewList();
listAdapter = new CustomAdapter(
getActivity(), newList);
gridView.setAdapter(listAdapter);
}
这里有几个问题:
我是否需要在 AsnycTask 类中使用 notifyDataSetChanged() 在我通过创建适配器的新实例来填充适配器后。
将按照上面的代码删除旧列表并替换为新列表。
我是否需要在 AsnycTask 类中使用 notifyDataSetChanged() 在 i 之后 通过创建适配器的新实例来填充适配器。
无需调用notifyDataSetChanged()
因为当前使用新数据源调用 ListView setAdapter
方法
是的,将按照上面的代码删除旧列表并替换为新列表。
列表视图将使用新数据填充。
注意:而不是再次调用setAdapter
方法-2 来显示新数据。 在适配器中创建一个方法,该方法将使用新数据更新当前适配器。
public void addNewItems(List<Objects> itemList){
1. clear data from current adapter
for example if using ArrayList then
ArrayList_Object.clearAll();
2. Add itemList in ArrayList_Object
ArrayList_Object.addAll(itemList);
3. Call this.notifyDataSetChanged()
}
现在调用 addNewItems
以使用填充 ListView 时首次创建的同一对象从AsnycTask
更新当前 apdater 数据:
listAdapter.addNewItems(newList)