Home » Android » android – How can one set a listener on a ListView that triggers whenever the list's data changes?

android – How can one set a listener on a ListView that triggers whenever the list's data changes?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have a ListView with a custom adapter. I want to attach a listener to this ListView that triggers whenever the data in the ListView changes, as that can happen a large variety of ways and I need another view to update whenever the ListView updates. Essentially I want this to trigger whenever notifyDataSetChanged() is called, either directly or indirectly (via add(), remove(), etc.):

Whenever an item in the list is removed, I want this to trigger.
Whenever an item is added to the list, I want this to trigger.
etc. etc.

Do I have to create my own listener to do this (and if so, a brief explanation of how would be very helpful) or is there a built-in way to listen to these events?

How to&Answers:

I actually found the solution:

_adapter = new CustomListAdapter(this.getActivity(), _list);
_adapter.registerDataSetObserver(new DataSetObserver()
{
   @Override
   public void onChanged()
   {
      // update other view
   }
});

Works exactly the way I’d hoped!