2016-06-11 62 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(); 
     } 
    }); 
} 

(只是一個粗略的例子,你可能需要根據你的需求來實現反邏輯)