首页 > 解决方案 > 在保持焦点的同时禁用 EditText 输入

问题描述

我有一个EditText字段,变量名valueInputField

我听文本输入的变化,我想要实现的是在输入过程中,当输入格式不匹配正则表达式时,我想停止显示更多输入,但保持字段集中&用户能够输入键盘仍然只是没有真正的效果会带到现场。

@OnTextChanged(R.id.value_input)
protected void onTextChanged(CharSequence charSequence) {
   String inputChars = charSequence.toString().trim();
   // if doesn't match regular expression, stop showing more inputs
   if (!inputChars.matches(MY_REGEXP)) {
      // this doesn't achieve what I need.
      valueInputField.setInputType(0)
   }
}

我试过上面的方法,它不起作用。如何实现我所需要的?

标签: androidandroid-edittext

解决方案


也许您应该尝试以下逻辑

maxLength=inputChars.length
if (!inputChars.matches(MY_REGEXP)) {
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
}

当与正则表达式不匹配时,上面的程序将设置 EditText 的最大长度。


推荐阅读