[Java] Button repeated hit prevention code

less than 1 minute read

Personal note ・Code for preventing repeated button hits *For reference, please verify by yourself. (Because of insufficient verification)

qiita.java



public class TestActivity {

   //! !! !! Please be aware that your notes are not fully tested! !! !!

   // Back key continuous hit prevention flag
   private boolean backKeyEnabled = true;

   @Override
   public boolean dispatchKeyEvent(KeyEvent event) {
     // button disabled if you try to hit repeatedly
     if(!backKeyEnabled) {
       return false;
     }
     // press the button
     backKeyEnabled = false;
     // Prevent pressing the button for a while
     new Handler().postDelayed(new Runnable() {
       @Override
       public void run() {
         backKeyEnabled = true; // enable pressing after 1 sec
       }
     }, 1000);

     // process later
   }
}