LinearLayout上的监听器

时间:2016-06-11 18:51:25

标签: java android

我已动态地将View添加到LinearLayout

我试图在LinearLayout个孩子的数量发生变化时进行检查,是否有这样的倾听者?

1 个答案:

答案 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();
        }
    });
}

(只是一个粗略的例子,你可能需要根据你的需要实现计数器逻辑)