Android开发中如何为30个EditText添加带输入校验的全局焦点监听器
批量实现所有填字输入框的统一焦点校验
之前单条监听失效的核心原因
你之前写的单个监听逻辑跑不通,本质是回调里没有把当前触发焦点事件的View实例传入校验流程,check()方法根本不知道该校验哪个输入框的内容,自然没法正确执行。
具体实现步骤
- 统一管理所有输入单元格的配置
不用零散定义campo0、campo1这类单独字段,把所有CampoCrossword实例存入同一个列表,后续遍历操作就行,30多个格子的代码量能缩到非常精简:List<CampoCrossword> allCells = new ArrayList<>(); allCells.add(new CampoCrossword(R.id.et_2_8_O, 'O')); allCells.add(new CampoCrossword(R.id.et_2_7_E, 'E')); allCells.add(new CampoCrossword(R.id.et_2_6_M, 'M')); // 剩余30个左右的单元格全部按上面的格式add进列表,不用单独定义变量 - 定义全局复用的焦点监听器
所有输入框的校验逻辑完全一致,只需要写一次监听器就行,不用重复写30多份匿名内部类:// 全局统一的焦点切换监听器 View.OnFocusChangeListener cellCheckListener = (view, hasFocus) -> { // 仅当输入框失去焦点时触发校验,获得焦点时不做处理 if (hasFocus) return; EditText currentEt = (EditText) view; int currentViewId = view.getId(); char rightChar = ' '; // 根据当前View的ID匹配对应正确答案 for (CampoCrossword cell : allCells) { if (cell.getViewId() == currentViewId) { rightChar = cell.getCorrectChar(); break; } } // 获取用户输入内容 String input = currentEt.getText().toString().trim(); char inputChar = input.isEmpty() ? ' ' : input.charAt(0); // 匹配结果设置背景色 if (inputChar == rightChar) { currentEt.setBackgroundColor(ContextCompat.getColor(this, R.color.green)); } else { currentEt.setBackgroundColor(ContextCompat.getColor(this, R.color.red)); } }; - 批量绑定监听器
遍历所有单元格配置,给对应ID的EditText绑定上面写好的统一监听器:for (CampoCrossword cell : allCells) { EditText targetEt = findViewById(cell.getViewId()); targetEt.setOnFocusChangeListener(cellCheckListener); }
优化提示
- 30多个格子的匹配循环完全不会有性能问题,如果想更高效,可以把正确答案存在以viewId为键的
SparseArray<Character>里,匹配时直接根据ID取值,不用遍历列表 - 如果
CampoCrossword实体类目前没有对外暴露viewId和正确字符的getter方法,补两个简单的get方法就能直接用 - 可以给EditText加输入长度限制,强制只能输入1个字符,避免用户多打内容导致校验逻辑判断错误
内容的提问来源于stack exchange,提问作者4ander
相关产品推荐
相关产品推荐

