如何检查视图是否有 children

How to check if a view has children

有没有办法检查视图是否有 children?例如...

boolean bool = view.hasChildren(); //returns true if view has one or more children

我需要知道这一点,因为我有一个空布局,我正在动态添加新视图,我需要知道布局是否为空。

试试这个:

for(int index=0; index<((ViewGroup)viewGroup).getChildCount(); ++index) {
    View nextChild = ((ViewGroup)viewGroup).getChildAt(index);
}

Is there a way to check if a view has children

假设是ViewGroup的子类,可以使用getChildCount()。例如

 public static boolean hasChildren(ViewGroup viewGroup) {
    return viewGroup.getChildCount() > 0;
 }

我们还需要检查视图是否可以有子视图。 例如,

    private int getViewsCount(View view){
        try{
            return ((ViewGroup) view).getChildCount();
        }catch(Exception e){
            return 0;
        }
    }

某些视图(例如 TextView 和 ImageView)无法转换为 ViewGroup,因此我们需要捕获该异常以避免运行时错误。