:使用递归和非递归编码实现统计一个ViewGroup中所包含的子View的个数?

  • 首先大家想到的肯定是递归实现,简单且较容易想到,代码如下:
/**
* 递归统计一个View的子View数(包含自身)
*
* @param root
* @return
*/
public int count1(View root) {
int viewCount = 0;

if (null == root) {
return 0;
}

if (root instanceof ViewGroup) {
viewCount++;
for (int i = 0; i < ((ViewGroup) root).getChildCount(); i++) {
View view = ((ViewGroup) root).getChildAt(i);
if (view instanceof ViewGroup) {
viewCount += count1(view);
} else {
viewCount++;
}
}
}

return viewCount;
}
  • 如果要求不用递归呢?那怎么实现呢?代码如下:
/**
* 非递归统计一个View的子View数(包含自身)
*
* @param root
* @return
*/
public int count(View root) {
int viewCount = 0;

if (null == root) {
return 0;
}

if (root instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) root;
LinkedList<ViewGroup> queue = new LinkedList<ViewGroup>();
queue.add(viewGroup);
while (!queue.isEmpty()) {
ViewGroup current = queue.removeFirst();
viewCount++;
for (int i = 0; i < current.getChildCount(); i++) {
if (current.getChildAt(i) instanceof ViewGroup) {
queue.addLast((ViewGroup) current.getChildAt(i));
} else {
viewCount++;
}
}
}
} else {
viewCount++;
}

return viewCount;
}

注释:非递归那就是树的广度优先遍历,每遍历到一个,计数器加一;

 

 遍历ViewGroup找出某种类型的所有子View

要求不能用递归的方式实现

// 遍历viewGroup
public void traverseViewGroup(View view) {
if(null == view) {
return;
}
if(view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
LinkedList<ViewGroup> linkedList = new LinkedList<>();
linkedList.add(viewGroup);
while(!linkedList.isEmpty()) {
ViewGroup current = linkedList.removeFirst();
//dosomething
for(int i = 0; i < current.getChildCount(); i ++) {
if(current.getChildAt(i) instanceof ViewGroup) {
linkedList.addLast((ViewGroup) current.getChildAt(i));
}else {
//dosomething
}
}
}
}else {
//dosomething
}
}