开发者

Best way to refill data in ListAdapter (ListView)

I do use this code for refill ListView wit开发者_Python百科h data after they change

// ListView lv;
// MyListAdapter la;
// DataClass dc;
dc.remove(object_id);
lv.setAdapter(la);

Is this the best way since we can't use notifyDataSetChanged() which is available only in ArrayAdapter ?

Solution

 //MyListAdapter.java

private ArrayList<DataSetObserver> observers = new ArrayList<DataSetObserver>();

public void registerDataSetObserver(DataSetObserver arg0) {
    observers.add(arg0);
}

public void unregisterDataSetObserver(DataSetObserver arg0) {
    observers.remove(arg0);
}

public void notifyDataSetChange() {
    for (DataSetObserver d : observers) {
        d.onChanged();
    }
}

public void remove(int position) {
    [DataClass object].remove(position);
    notifyDataSetChange();
} 


For a CursorAdapter I use the following code:

mAdapter.getCursor().requery();

If you are using custom adapter or as you commented: only want ListAdapter as member variable. Instead of using private CustomAdapter mAdapter; (which i would recommended to avoid creating unnecessary objects).

You can use DataSetObserver part and ListAdapter.registerDataSetObserver(DataSetObserver observer). DataSetObserver.onChanged() will be called by the BaseAdapter implementation, so it should work for all adapter.

BaseAdapter.notifyDataSetChanged():

public void notifyDataSetChanged() {
    mDataSetObservable.notifyChanged();
}


You can use ArrayAdapter, which accepts Lists instead of Arrays. This way you can use notifyDataSetChanged() on it.


It seems that you think something wrong as I was did. As you know, ListAdapter hasn't notifyDataSetChanged.

It seems that Cursor is the best match with a ListView. Doc. says that "Frequently that data comes from a Cursor, but that is not required. The ListView can display any data provided that it is wrapped in a ListAdapter." If you check both links registerDataSetObserver ([DataSetObserver]2 observer), you can notice something. ListAdapter go well with a cursor. So why don't you try to use other adapters.

I think the best way to refresh adapter is using or extending BaseAdapter(with ListView). And use notifyDataSetChanged after change your dataset. In my case it works well and softly(invalidating list view and items, and scroll position is just there! Not going to first position).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜