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.
public class SingleClick
{
bool hasClicked;
#region Button Click
Action < object, EventArgs > _setClick;
public SingleClick(Action < object, EventArgs > setClick)
{
_setClick = setClick;
}#endregion Button Click
public void Click(object s, EventArgs e)
{
if (!hasClicked)
{
_setClick(s, e);
hasClicked = true;
}
Reset();
}
async void Reset()
{
await Task.Delay(800);
await Task.Run(new Action(() => hasClicked = false));
}
}
Usage :
var button = new Button();
button.Clicked += new SingleClick(Button_Clicked).Click;
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.
public class SingleClick
{
bool hasClicked;
#region Button Click
Action < object, EventArgs > _setClick;
public SingleClick(Action < object, EventArgs > setClick)
{
_setClick = setClick;
}#endregion Button Click
public void Click(object s, EventArgs e)
{
if (!hasClicked)
{
_setClick(s, e);
hasClicked = true;
}
Reset();
}
async void Reset()
{
await Task.Delay(800);
await Task.Run(new Action(() => hasClicked = false));
}
}
Usage :
var button = new Button();
button.Clicked += new SingleClick(Button_Clicked).Click;
Comments
Post a Comment