这次遇到一个需求,需要计算当前View的深度,基本上就是大学时候数据结构里求二叉树的解法,记录一下,理论上也可以用于性能优化和性能监控
private int maxDeep(View view) {
//view不会有子view所以就返回0
if (!(view instanceof ViewGroup)) {
return 0;
}
ViewGroup viewGroup = (ViewGroup) view;
//是viewgroup如果并没有子view,那么也是最底层的view
if (viewGroup.getChildCount() == 0) {
return 0;
}
//记录最大层数
int max = 0;
//广度遍历view
for (int i = 0; i < viewGroup.getChildCount(); i++) {
//如果viewGroup拥有子view,所以层数+1,然后递归算它的子view的层数
int deep = maxDeep(viewGroup.getChildAt(i)) + 1;
//取最大值
max = Math.max(deep,max);
}
return max;
}