【问题标题】:TextWatcher works but after text changed notTextWatcher 有效,但文本更改后没有
【发布时间】:2014-05-11 22:07:47
【问题描述】:

这是我控制用户出生年份输入的文本观察器。如果用户输入小于 1900 我想用 1900 替换它。应用程序正常工作。我可以输入一个值到TextView。但是当开始输入时以“1”开头,然后在我无法再次编辑TextView 后立即替换为“1900”。键盘上的删除按钮不会删除输入的值。

@Override
        public void afterTextChanged(Editable s) {

            try {
                int birth = Integer.parseInt(s.toString());

                if (birth < 1900) {
                    s.replace(0, s.length(), "1900");
                }

            } catch (NumberFormatException e) {
            }

        }

<EditText
    android:id="@+id/editText1"
    android:hint="Birth Year"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="numberSigned">
</EditText>

【问题讨论】:

    标签: android textview textwatcher


    【解决方案1】:

    好吧,我的朋友,我已经考虑了一段时间,这是我能得到的最接近的解决方案。试试这个

    @Override
            public void afterTextChanged(Editable s) {
    
                try {
                    int birth = Integer.parseInt(s.toString());
    
                    if (birth < 1900 && s.length()>=4) {
                        s.replace(0, s.length(), "1900");
                    }
    
                } catch (NumberFormatException e) {
                }
    
            }
    

    这只是对 if 语句的一个小修改。

    【讨论】:

      【解决方案2】:
      replacing to "1900" after I can't edit TextView again. Delete button on keypad does not delete entered value.
      

      这是预期的行为,这并不意味着键盘上的删除按钮不会删除重新输入的值,因为在您将1替换为1900然后尝试删除0(最后一位)将被删除并立即使用输入 190 调用 afterTextChanged,因此您的条件再次满足 &lt;1900 并且文本再次替换为 1900(当您尝试删除时继续此操作)。

      我建议添加检查以查看输入的minimum length,我相信您希望用户至少输入4 digit

       public void afterTextChanged(Editable s) {
      
          if(s.toString().length < 4) {
              return;
          }
            // do your other logic here
      
       }
      

      【讨论】:

        猜你喜欢
        • 2011-11-18
        • 2017-05-05
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 2017-05-09
        • 2020-09-23
        • 2021-11-19
        • 2021-02-03
        相关资源
        最近更新 更多