我已动态地将View
添加到LinearLayout
。
我试图在LinearLayout
个孩子的数量发生变化时进行检查,是否有这样的倾听者?
答案 0 :(得分:2)
看看ViewGroup.OnHierarchyChangeListener。
使用带有计数器的onChildViewAdded()
和onChildViewRemoved()
方法来跟踪ViewGroup
的子计数。
您可以在Activity
中执行以下操作:
private childCount;
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
final LinearLayout layout = (LinearLayout) findViewById(R.id.yourLayout);
childCount = layout.getChildCount();
layout.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
@Override
public void onChildViewAdded(View parent, View child) {
childCount++;
//childCount = layout.getChildCount(); //a safer but slower approach
}
@Override
public void onChildViewRemoved(View parent, View child) {
childCount--;
//childCount = layout.getChildCount();
}
});
}
(只是一个粗略的例子,你可能需要根据你的需要实现计数器逻辑)