Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Listener/Callback for when number of View children changes

In Android can one use/implement a listener that fires a callback when the number of children for a given View changes dynamically? Say for example a View has 3 immediate children, and one is removed through code, I need an event to fire to say that the number of immediate children has changed.

To clarify, I don't need to perform a depth traversal on the View tree to count children, I'm just interested in counting the number of children at the first layer of a given View.

Many thanks

like image 570
Darius Avatar asked Sep 26 '12 15:09

Darius


2 Answers

I believe that you want to use the OnHierarchyChangeListener:

Interface definition for a callback to be invoked when the hierarchy within this view changed. The hierarchy changes whenever a child is added to or removed from this view.

It has two callbacks:

  • onChildViewAdded()
  • onChildViewRemoved()
like image 141
Sam Avatar answered Sep 30 '22 06:09

Sam


Its simple to trick down.

  1. Just extend the View Group Your adding View Into and override remove and optionally the addView method.

  2. Provide Your Callback Interface Implementation to the any of Your ViewGroup class method to set listener. Call its delegate from within the overridden remove and addView method. Make your Callback Interface delegate to receive current size.

Something like this

public class MyViewGroup extends LinearLayout {

  // provide constructor implmentation to justify super constructor requirement

  private OnSizeChangeListener callback;

  public void setOnSizeChangeListener(OnSizeChangeListener callback) {
     this.callback = callback;
  }

  @Override
  public void remove(View view) {
    super.remove(view);
    if(callback != null) {
       callback.sizeChanged(getChildCount);
    }
  }   
}
like image 24
Rohit Sharma Avatar answered Sep 30 '22 05:09

Rohit Sharma