It is a common problem for android or any mobile developer,
to stop unwanted multi tap in a button or view. This may cause blockers and
crashes also. So, it’s a kind of serious and common issue. To fix this there
are multiple solutions you can approach to. You can use timer or you can track
down view event or even you can use a flag also. But again you have to change
the flag after the button click occurrence. You can assign a different handler
after first click. But also again you have to assign the real handler after the
click occurs. All these may not give you 100% solution; as well it can be
another piece of code for a new error.
Here I found a solution which may solve this issue in much
secure and smart way.
Note: Same idea will work for Android Java developers.
Let get in to it-
Step 1: Create SingleClickListener class, with following
code.
public class SingleClickListener
{
public SingleClickListener(Action<object, EventArgs> setOnClick)
{
_setOnClick = setOnClick;
}
private bool hasClicked;
private Action<object, EventArgs> _setOnClick;
public void OnClick(object v, EventArgs e)
{
if (!hasClicked)
{
_setOnClick(v, e);
hasClicked = true;
}
reset();
}
private void reset()
{
Android.OS.Handler mHandler = new Android.OS.Handler();
mHandler.PostDelayed(new Action(() => {
hasClicked = false; }), 500);
}
}
Step2: Use it everywhere you need it, in following way-
Button myButton= FindViewById<Button> (Resource.Id.myButton);
myButton.Click += new SingleClickListener( myButtonClickEvent).OnClick;
void myButtonClickEvent (object sender, EventArgs e)
{
//your button click code
goes here.
}
That’s it. :)
1 comment:
Hello,
thanks for this solution. I think it's better to switch the following lines :
_setOnClick(v, e);
hasClicked = true;
it's preferable to change the boolean value as soon as possible :
hasClicked = true;
_setOnClick(v, e);
Laurent
Post a Comment