Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Android double tap on Xamarin Forms Label

Hey so I'm working Xamarin Forms and I'm dealing with the issue of android double tap.

My problem is that I'm using a label as button - and when I click this rapidly, the app will crash. I want to prevent this by disabling tapping after this is clicked.

My Label is defined in the XAML like this:

<Label x:Name="LabelName" Text="LabelText"/>

And my code-behind is like this:

LabelName.GestureRecognizers.Add((new TapGestureRecognizer
{
  Command = new Command(async o =>
  {
    await Navigation.PopToRootAsync();
  })
}));
like image 379
stepheaw Avatar asked Dec 15 '22 08:12

stepheaw


2 Answers

Well, you can have an external boolean to avoid that (also, not sure but disabling temporarily the Label may work):

//On the form, so you can use a reference to This, else this is a value variable and will be copied and false always
bool disable = false; 

And then:

LabelName.GestureRecognizers.Add((new TapGestureRecognizer
{
  Command = new Command(async o =>
  {
     if(this.disable)
       return;

     this.disable = true;

    await Navigation.PopToRootAsync();

    this.disable = false;
 })
}));
like image 110
Gusman Avatar answered Jan 02 '23 12:01

Gusman


On Android, the UI registers multiple taps and queues them up to execute one after the other. So double tapping on a button can execute the command twice and cause unintended behavior. The simplest way is to have your commands observe a bool property and toggle that property on/off. Something like this,

SomeCommand = new Command (OnCommand,(x)=> CanNavigate);

async void OnCommand (object obj)
{
        CanNavigate = false;

        await CurrentPage.DisplayAlert ("Hello", "From intelliAbb", "OK");

        CanNavigate = true;

}

You can checkout the complete example at https://intelliabb.com/2017/02/18/handling-multiple-taps-in-xamarin-forms-on-android/

like image 20
hnabbasi Avatar answered Jan 02 '23 11:01

hnabbasi