How can one set a listener on a ListView that triggers whenever the list's data changes?
Asked Answered
S

1

9

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?

Strontia answered 3/3, 2015 at 3:30 Comment(0)
S
25

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!

Strontia answered 3/3, 2015 at 3:41 Comment(2)
This is great if you're doing requests over the network, and need to be notified when the data has arrived (for example to hide a progress bar).Rummage
It works too when you use services, put this listener to end or show a messagem for user. Great answer.Renata

© 2022 - 2024 — McMap. All rights reserved.