Mike G
Mike G

Reputation: 4959

Can the parent view be notified when a child is created

In android UI can be created dynamically so is there a way to know if a child was created to a parent ?

For example, if i have a linear layout as a parent and i dynamically create a child button. Is there away to notify the parent ?

Upvotes: 0

Views: 411

Answers (2)

Kevin Coppock
Kevin Coppock

Reputation: 134714

Tal Kanel's version will work, but to avoid repeating code, I'd suggest using a HierarchyChangeListener:

LinearLayout ll = (LinearLayout)findViewById(R.id.mylinearlayout);
ll.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
    public void onChildViewAdded(View parent, View child) {
        //handle the logic for an added child here
    }    
    public void onChildViewRemoved(View parent, View child) {
        //optionally, handle logic for a removed child
    }
});

Upvotes: 3

Tal Kanel
Tal Kanel

Reputation: 10785

It's simple - if you have LinearLayout name linearLayout1, the only why to add child to him is by calling the linearLayout.addView(View child) method. so, you know exactly when the child added: it's can be only after this method called :) example:

linearLayout1.addView(view);
doWhatYouWantToDoWhenChildAdded();

Upvotes: 1

Related Questions