Search code examples
androidandroid-adapterandroid-adapterview

Custom AdapterView respond to its adapter's notifyDataSetChanged()


I am creating a custom adapter view. What I'm missing as a final step is to make it respond to its adapter's notifyDataSetChanged() method.

When the data change e.g.:

myArrayOfData.remove(0); // remove first object
myAwesomeAdapter.notifyDataSetChanged();

I have to create a layout with the new, updated, data.

My question is should I add a listener (if so which listener and binded on which object)? Or should I override a method in my AdapterView (if so which)? I find the docs quite blurry here.

After the AdapterView has been notified for the changes as well, I will redraw the layout e.g. requestLayout();


Solution

  • You should override the setAdapter method in your custom AdapterView and register/unregister a DataSetObserver, something like:

    private DataSetObserver mDataObserver = new DataSetObserver() {
            @Override
            public void onChanged() {
                requestLayout();
            }
    
            @Override
            public void onInvalidated() {
                requestLayout();
            }
        };
    
        @Override
        public void setAdapter(ListAdapter adapter) {
            if(mAdapter != null) {
                mAdapter.unregisterDataSetObserver(mDataObserver);
            }
            mAdapter = adapter;
            mAdapter.registerDataSetObserver(mDataObserver);
        }