Kurlicue Kurlicue - 5 months ago 18
Java Question

Listeners on LinearLayout

I'm adding and removing views to a Linearlayout dynamically.

I'm trying to check whenever a LinearLayout's number of childs changes, is there such a listener?

Answer

Take a look at ViewGroup.OnHierarchyChangeListener.

Use it's onChildViewAdded() and onChildViewRemoved() methods with a counter to keep track of the child count of a ViewGroup.

You could do something like this in your Activity:

private childCount;

// ...

@Override
protected void onCreate(Bundle savedInstanceState) {

    // ...

    LinearLayout layout = (LinearLayout) findViewById(R.id.yourLayout);

    childCount = layout.getChildCount();

    layout.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
        @Override
        public void onChildViewAdded(View parent, View child) {
            childCount++;
        }

        @Override
        public void onChildViewRemoved(View parent, View child) {
            childCount--;
        }
    });
}

(this is just a rough example, you may need to implement the counter logic completely differently according to your needs)