1. 获取子view
编历布局,看当前布局有几个EditText
,然后去监听拿到focus
的view
获取子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. 总结
看起来很呆,但是实际开发中尤其是在有自己需要手写的收集表单中确实有用,如果你的表单中个别内容不需要监听,直接在监听的方法中返回的文字默认都不为空即可。