Kurlicue Kurlicue - 4 months ago 5
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?


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;

// ...

protected void onCreate(Bundle savedInstanceState) {

    // ...

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

    childCount = layout.getChildCount();

    layout.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
        public void onChildViewAdded(View parent, View child) {

        public void onChildViewRemoved(View parent, View child) {

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