android editText: detect when user stops editing

Buda Gavril picture Buda Gavril · Mar 19, 2013 · Viewed 8.1k times · Source

I have an editText which represent an input for a search criteria. I want to know if there is a way to detect when user stops editing this editText so I can query the db for data for my list. For example, if the user types "test" I want to be notified only after user has typed the word, not after user types each letter, like text watcher does. Do you have any ideas? I would avoid to use some timer to measure milliseconds elapsed between key pres events.

Answer

eski picture eski · Mar 19, 2013

Not incredibly elegant, but this should work.

Initializations:

long idle_min = 4000; // 4 seconds after user stops typing
long last_text_edit = 0;
Handler h = new Handler();
boolean already_queried = false;

Set up your runnable that will be called from the text watcher:

private Runnable input_finish_checker = new Runnable() {
    public void run() {
            if (System.currentTimeMillis() > (last_text_edit + idle_min - 500)) {
                 // user hasn't changed the EditText for longer than
                 // the min delay (with half second buffer window)
                 if (!already_queried) { // don't do this stuff twice.
                     already_queried = true;
                     do_stuff();  // your queries
                 }
            }
    }
};

Put this in your text watcher:

last_text_edit = System.currentTimeMillis();
h.postDelayed(input_finish_checker, idle_min);