Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class TextDelayWatcher implements TextWatcher {
- private OnActionListener onActionListener;
- private Handler handler;
- @Nullable
- private Timer timer;
- @Nullable
- private Runnable runnable;
- public TextDelayWatcher(OnActionListener onActionListener) {
- this.onActionListener = onActionListener;
- this.handler = new Handler();
- }
- @Override
- public void afterTextChanged(final Editable arg0) {
- // user typed: start the timer
- timer = new Timer();
- timer.schedule(new TimerTask() {
- @Override
- public void run() {
- runnable = new Runnable() {
- @Override
- public void run() {
- onActionListener.onAction(arg0);
- }
- };
- handler.post(runnable);
- }
- }, 400); // 600ms delay before the timer executes the „run“ method from TimerTask
- }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- // nothing to do here
- }
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- // user is typing: reset already started timer (if existing)
- clear();
- }
- public void onDestroy() {
- clear();
- onActionListener = null;
- }
- public void clear() {
- if (timer != null) {
- timer.cancel();
- timer = null;
- }
- if (runnable != null) {
- handler.removeCallbacks(runnable);
- runnable = null;
- }
- }
- public interface OnActionListener {
- void onAction(Editable editable);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement