-1

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?

Iñigo
  • 1,877
  • 7
  • 25
  • 55
pledgeX
  • 443
  • 3
  • 11
  • 1
    `I think the best solution would be to wait until the focus moves off` then you should be using a focus changed listener : https://stackoverflow.com/questions/10625775/android-on-focus-change – a_local_nobody Aug 02 '19 at 10:35
  • Any feedback as to why this was down-voted? I don't mind, I just want to understand so I can improve future questions. – pledgeX Sep 04 '19 at 21:58

3 Answers3

0

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 )
    }
0

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)
Ramees Thattarath
  • 1,093
  • 11
  • 19
0

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