Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. public class TextDelayWatcher implements TextWatcher {
  2.  
  3. private OnActionListener onActionListener;
  4. private Handler handler;
  5. @Nullable
  6. private Timer timer;
  7. @Nullable
  8. private Runnable runnable;
  9.  
  10. public TextDelayWatcher(OnActionListener onActionListener) {
  11. this.onActionListener = onActionListener;
  12. this.handler = new Handler();
  13. }
  14.  
  15. @Override
  16. public void afterTextChanged(final Editable arg0) {
  17. // user typed: start the timer
  18. timer = new Timer();
  19. timer.schedule(new TimerTask() {
  20. @Override
  21. public void run() {
  22. runnable = new Runnable() {
  23. @Override
  24. public void run() {
  25. onActionListener.onAction(arg0);
  26. }
  27. };
  28. handler.post(runnable);
  29. }
  30. }, 400); // 600ms delay before the timer executes the „run“ method from TimerTask
  31. }
  32.  
  33. @Override
  34. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  35. // nothing to do here
  36. }
  37.  
  38. @Override
  39. public void onTextChanged(CharSequence s, int start, int before, int count) {
  40. // user is typing: reset already started timer (if existing)
  41. clear();
  42. }
  43.  
  44. public void onDestroy() {
  45. clear();
  46. onActionListener = null;
  47. }
  48.  
  49. public void clear() {
  50. if (timer != null) {
  51. timer.cancel();
  52. timer = null;
  53. }
  54. if (runnable != null) {
  55. handler.removeCallbacks(runnable);
  56. runnable = null;
  57. }
  58. }
  59.  
  60. public interface OnActionListener {
  61. void onAction(Editable editable);
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement