Workaround To Prevent Rapid Clicks On a Button in Xamarin Forms

Things developers face while programming: We have seen rapid clicking on a button invoking the same event or the same process many times. Here we will find a way to control the rapid click error of a button.

We can write a class named SingleClick, in which we will write a method, Click with Object and EventArgs, as arguments to do the magic. Refer to the below code snippet for more.

  1. public class SingleClick  
  2. {  
  3.     bool hasClicked;  
  4.     #region Button Click  
  5.     Action < object, EventArgs > _setClick;  
  6.     public SingleClick(Action < object, EventArgs > setClick)  
  7.     {  
  8.         _setClick = setClick;  
  9.     }#endregion Button Click  
  10.   
  11.     public void Click(object s, EventArgs e)   
  12.     {  
  13.         if (!hasClicked)  
  14.         {  
  15.             _setClick(s, e);  
  16.             hasClicked = true;  
  17.         }  
  18.         Reset();  
  19.     }  
  20.     async void Reset()   
  21.     {  
  22.         await Task.Delay(800);  
  23.         await Task.Run(new Action(() => hasClicked = false));  
  24.     }  
  25. }  
Usage :
  1. var button = new Button();  
  2. button.Clicked += new SingleClick(Button_Clicked).Click;  
Try this workaround and give me your valuable suggestions. Happy Coding.

 

Next Recommended Reading Xamarin.Forms Floating Action Button