How to add delay before presenting error message on EditText field?

I’ve got some straightforward regex validation on an editText element. The problem I have is that the error shows immediately if it fails the validation (even if the user is still typing), which isn’t nice UX. Here’s the code currently.

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");
        }
    }
}

I think the best solution would be to wait until the focus moves off the editText element before running the above validation. Alternatively, we could wait for X milliseconds since the last input before running the validation, or just add some nasty hardcoded delay in there.

Any suggestions?

3
Leave a Reply

avatar
3 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

You can do it with Handler. Change TIME_DELAY as per your requirement. Define time delay (1000 means 1 sec) in the class level. I have modified the code as per your requirement.Here i have added 2 sec delay. You can go with it. 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 ) }

Jason
Guest

You can achieve this by using Handler.postDelayed method private Handler handler = new Handler() private Runnable runnable = new Runnable() { public void run() { timeEditText.setError("Not a valid time"); } } and inside onCreate create below text watcher and attach to edit text TextWatcher tw = new TextWatcher() { public void afterTextChanged(Editable s) { timeEditText.setError(null) handler.removeCallbacks(runnable) if (!validTimepattern.matcher(currentTime).matches()){ handler.postDelayed(runnable,3000) } } } and in ondestroy add below line to avoid crashes when activty gets destroyed handler.removeCallbacks(runnable)

Jason
Guest

If you want to pause the execution for a while (eg: milliseconds), you can use
SystemClock.sleep(3000);