2016-06-11 53 views

回答

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

(只是一个粗略的例子,你可能需要根据你的需求来实现反逻辑)