从Adapter内部调用notifyDataSetChanged()

时间:2015-01-27 04:15:46

标签: android listview android-arrayadapter

ArrayAdapter的实现是这样的,它会监听下位数据的变化。因此,数据中的任何更改都会通知适配器并调用notifydataSetChanged()

public class MyAdapter extends ArrayAdapter implements ObjectStateListener {

    @Override
    public void onObjectStateChanged() {
        /*Call appropriate functions as the underlying data as changed.
        A good way of doing that would be to retrieve only the positions of the filtered values
        so that the original dataholder can be used but display only certain indices
         */
        Log.v(TAG, "FilterCriteria changed. Trigger fired");
        this.filterPositions = Helper().getFilteredPositions(filterCriteria, mAppartments);

        Log.v(TAG, "CALLING NOTIFYDATASETCHANGED()...");
        notifyDataSetChanged();
        Log.v(TAG, "FINISHED CALLING NOTIFY DATASET CHANGED");

    }
}

在上面的代码中,只要数据发生变化,就会调用函数onObjectStateChanged(),然后调用notifyDataSetChanged()。为了测试onObjectStateChanged()是否被正确调用,我已经放了一堆Log语句,你可以看到。所有这些日志都出现在logcat中。但是在调用getView()后没有调用notifyDataSetChanged(),因此列表视图没有被刷新。

为什么会这样? notifyDataSetChanged()应该确保调用getView()并且新数据会反映在ListView中吗?

ObjectStateChangeListener

的定义
public interface ObjectStateListener {

    public void onObjectStateChanged();
    public void listenForStateChange(Object o);
}

3 个答案:

答案 0 :(得分:-1)

如果要在列表中删除或插入新值,那么每当适配器列表发生更改时,都会调用notifystatechange(),因此在插入或删除值调用notifystatechange()之后,它将刷新listview。

答案 1 :(得分:-1)

我不得不停止在我的AutoCompleTextViews上使用notifyDataSetChanged(),因为它们也没有刷新。我只保留适配器的本地副本,然后在更改时使用新数据集重置它。

确保您的ArrayAdapter设置为在更改时通知(默认情况下),并且您在技术上甚至不需要根据文档调用notifyDataSetChanged():http://developer.android.com/reference/android/widget/ArrayAdapter.html

答案 2 :(得分:-1)

首先更新您在适配器中保留它的引用的数据,然后调用notifyDataSetChanged()。您还必须传递新数据。

相关问题