当孩子创建时可以通知父视图

问题描述:

在android UI中可以动态创建,所以有办法知道孩子是否创建为父级?当孩子创建时可以通知父视图

例如,如果我有一个线性布局作为家长,我动态地创建一个子按钮。有没有通知父母?

+2

你的问题不是很清楚,你想要做什么? – Ricky

+0

为什么你想通知一个线性布局,添加一个孩子? – Arkde

这很简单 - 如果您有LinearLayout名称linearLayout1,唯一的原因是通过调用linearLayout.addView(View child)方法向其添加子对象为 。 所以,你知道什么时候孩子说:这可能是只有在调用此方法:) 例如:

linearLayout1.addView(view); 
doWhatYouWantToDoWhenChildAdded(); 

塔尔Kanel的版本将工作,但要避免重复代码,我建议使用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 
    } 
}); 
+0

+1不知道这件事。 – Ricky

+0

你的回答对我来说似乎更好,然后是我的答案,但不是因为重复代码问题:通过使用onHierarchyChangeListener,你可以真正确定这个孩子可以很快地添加。 –