一个监听所有内置Edittext的ViewGroup

1. 获取子view

编历布局,看当前布局有几个EditText,然后去监听拿到focusview

获取子view的方式:

// 遍历viewGroup
    public int traverseViewGroup(View view) {
        int viewCount = 0;
        if (null == view) {
            return 0;
        }
        if (view instanceof ViewGroup) {
            //遍历ViewGroup,是子view加1,是ViewGroup递归调用
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View child = ((ViewGroup) view).getChildAt(i);
                if (child instanceof ViewGroup) {
                    viewCount += traverseViewGroup(((ViewGroup) view).getChildAt(i));
                } else {
                    viewCount++;
                }
            }
        } else {
            viewCount++;
        }
        return viewCount;
    }

非递归方法获取子view

 // 遍历viewGroup
    public int traverseViewGroup(View view) {
        int viewCount = 0;
        if (null == view) {
            return 0;
        }
        if (view instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) view;
            LinkedList<ViewGroup> linkedList = new LinkedList<>();
            linkedList.add(viewGroup);
            while (!linkedList.isEmpty()) {
                //removeFirst()删除第一个元素,并返回该元素
                ViewGroup current = linkedList.removeFirst();
                viewCount++;
                //遍历linkedList中第一个viewGroup中的子view
                for (int i = 0; i < current.getChildCount(); i++) {
                    if (current.getChildAt(i) instanceof ViewGroup) {
                        linkedList.addLast((ViewGroup) current.getChildAt(i));
                    } else {
                        viewCount++;
                    }
                }
            }
        } else {
            viewCount++;
        }
        return viewCount;
    }

获取到子view的时候,你需要判断这个子view是不是EditText,方法有两种:

v.getClassName() == "EditText"
v instanceof Button

2. 拿到子view之后:

方法1. 拿到子view之后,不需要每个都去监听(当然你也可以这么做),另外一种,判断在viewgroup中哪个子view获取到了焦点,然后给他添加监听,其他的移除监听。

然后给设置的按钮去设置enable

方法2. LiveData监听数据变化,但是和上面的方式换汤不换药,代码量更多了一点。LiveData的具体使用可以参考: https://developer.android.google.cn/reference/android/arch/lifecycle/LiveData

3. 总结

看起来很呆,但是实际开发中尤其是在有自己需要手写的收集表单中确实有用,如果你的表单中个别内容不需要监听,直接在监听的方法中返回的文字默认都不为空即可。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值