【问题标题】:Not understanding whether to use notifyDataSetChanged() when elements in listview are updated?不了解更新列表视图中的元素时是否使用 notifyDataSetChanged()?
【发布时间】:2015-04-23 04:54:37
【问题描述】:

我有一个使用带有自定义对象适配器的 listview 的 android 应用程序。

如果对象列表可用,则活动的 onCreate 我用以前的对象填充适配器并进行异步调用以获取新对象并填充适配器。

当再次填充适配器时,旧的元素列表将被删除并添加新的元素。我没有使用 notifyDataSetChanged()。

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);

            }

这里有几个问题:

  1. 通过创建适配器的新实例来填充适配器后,是否需要在 AsnycTask 类中使用 notifyDataSetChanged()。

  2. 是否会按照上述代码删除旧列表并用新列表替换。

【问题讨论】:

  • 如果您正在创建新实例,则无需使用 notifyDataSetChanged() .....
  • 旧列表将被新列表替换..
  • 你真正想要什么?你想用新的东西删除旧的项目还是想保留两者?
  • @MurtazaKhursheedHussain 删除旧项目并用我展示的异步类中的新项目替换...

标签: android listview android-listview


【解决方案1】:

我是否需要在我之后在 AsnycTask 类中使用 notifyDataSetChanged() 通过创建适配器的新实例来填充适配器。

无需调用notifyDataSetChanged(),因为当前使用新数据源为ListView 调用setAdapter 方法

是否会按照上述代码删除旧列表并用新列表替换。

是的,ListView 将填充新数据。

注意: 而不是再次调用setAdapter 方法-2 来显示新数据。在 Adapter 中创建一个方法,该方法将使用新数据更新当前 Adapter。例如:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多