Examples of three ways Android prevents repeated clicks

  • 2021-08-31 09:04:12
  • OfStack

In the project, we often encounter the problem of preventing repeated clicks on buttons and custom controls, such as Item. Let's make a summary below.

Method 1: throttleFirst () using RxJava

The specific code is as follows:


  /**
   *  Prevent repeated clicks 
   *
   * @param target  Objectives view
   * @param listener  Listener 
   */
  public static void preventRepeatedClick(final View target, final View.OnClickListener listener) {
    RxView.clicks(target).throttleFirst(1, TimeUnit.SECONDS).subscribe(new Observer<Object>() {
      @Override
      public void onCompleted() {

      }

      @Override
      public void onError(Throwable e) {

      }

      @Override
      public void onNext(Object object) {
        listener.onClick(target);
      }
    });
  }

In the above code, throttleFirst method is used to take the first click within 1 second to respond.

Method 2: Using system time difference


  // Global definition 
  private long lastClickTime = 0L;
  private static final int FAST_CLICK_DELAY_TIME = 500; //  Fast click interval 

  // In setting Item When listening in 
  item.setOnItemClickListener(xxx){
    if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME){
      return;
    }
    lastClickTime = System.currentTimeMillis();

    // Do other operations below, such as jumping and so on 
    XXX
  }

This method is mainly aimed at clicking custom controls.

Method 3: Tool class, which is used to determine whether to click quickly

The principle of this method is similar to that of method 2:


private static final int MIN_DELAY_TIME= 1000; //  The interval between two clicks cannot be less than 1000ms
  private static long lastClickTime;

  public static boolean isFastClick() {
    boolean flag = true;
    long currentClickTime = System.currentTimeMillis();
    if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
      flag = false;
    }
    lastClickTime = currentClickTime;
    return flag;
  }

Related articles: