Kurlicue Kurlicue -5 years ago 149
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 Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download