【问题标题】:How to add delay before presenting error message on EditText field?如何在 EditText 字段上显示错误消息之前添加延迟?
【发布时间】:2019-08-02 10:30:18
【问题描述】:

我对 editText 元素进行了一些简单的正则表达式验证。我遇到的问题是,如果验证失败(即使用户仍在键入),错误会立即显示,这不是很好的 UX。这是当前的代码。

TextWatcher tw = new TextWatcher() {
    public void afterTextChanged(Editable s) {
        String currentTime = t_timeEditText.getText().toString();
        if (!validTimepattern.matcher(currentTime).matches()){
            timeEditText.setError("Not a valid time");
        }
    }
}

我认为最好的解决方案是等到焦点从 editText 元素移开后再运行上述验证。或者,我们可以在运行验证之前等待自上次输入以来的 X 毫秒,或者只是在其中添加一些讨厌的硬编码延迟。

有什么建议吗?

【问题讨论】:

标签: java android error-handling android-edittext


【解决方案1】:

你可以用 Handler 来做。根据您的要求更改 TIME_DELAY。在班级级别定义时间延迟(1000 表示 1 秒)。我已根据您的要求修改了代码。在这里我添加了 2 秒的延迟。你可以随它去。

val TIME_DELAY : Int = 2000
if (!validTimepattern.matcher(currentTime).matches()){

    Handler().postDelayed(object : Runnable{
                    override fun run() {
         timeEditText.setError(“Not a valid time”);
                    }
                }, TIME_DELAY )
    }

【讨论】:

    【解决方案2】:

    您可以通过使用 Handler.postDelayed 方法来实现这一点

     private Handler handler = new Handler()
    
        private Runnable runnable  = new Runnable() {
          public void run() 
            { 
               timeEditText.setError("Not a valid time");
            } 
    
        }
    

    在 onCreate 内部创建文本观察器并附加到编辑文本

    TextWatcher tw = new TextWatcher() {
        public void afterTextChanged(Editable s) {
               timeEditText.setError(null)
             handler.removeCallbacks(runnable)
    
            if (!validTimepattern.matcher(currentTime).matches()){
                 handler.postDelayed(runnable,3000)
            }
        }
    }
    

    并在 ondestroy 中添加以下行以避免活动被破坏时崩溃

     handler.removeCallbacks(runnable)
    

    【讨论】:

      【解决方案3】:

      如果你想暂停执行一段时间(例如:毫秒),你可以使用 SystemClock.sleep(3000);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-08
        • 2022-08-08
        • 2013-02-26
        相关资源
        最近更新 更多