统计一个ViewGroup中包含的子View的个数(递归和非递归实现)

:使用递归和非递归编码实现统计一个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
	}
}

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值