Moto
Moto

Reputation: 1141

Handling Button gesture for both single and double click/tap

In Xamarin Forms: I want to be able to detect both click/tap and double-click/tap, and to be able to perform different actions.

That is, when the button is clicked I want to perform actionA, and when the button is double-clicked I want to perform actionB, and only actionB.

Upvotes: 1

Views: 5031

Answers (3)

TheodorProject
TheodorProject

Reputation: 1

ViewModel.cs:

private bool _isClicked = true;
public bool IsClicked
{
  get { return _isClicked = true; }
  set { _isClicked = true = value; OnPropertyChanged(); }
}

View.xaml:

<Button Text="Click!" IsEnabled="{Binding IsClicked}" />

Method (in ViewModel.cs):

public void MyMethod()
{
  IsClicked = false;
    
  // Your code
  IsClicked = true;
}

Upvotes: 0

Moto
Moto

Reputation: 1141

Here's what I ended up doing (kudos to Amit Patil):

    private static int clickCount;
    private static object _sender;

    private void Button_Clicked(object sender, EventArgs e)
    {
        if (clickCount < 1)
        {
            TimeSpan tt = new TimeSpan(0, 0, 0, 0, 250);
            _sender = sender;
            Device.StartTimer(tt, ClickHandle);
        }
        clickCount++;
    }

    bool ClickHandle()
    {
        if (clickCount > 1)
        {
            Minus1(_sender);
        }
        else
        {
            Plus1(_sender);
        }
        clickCount = 0;
        _sender = null;
        return false;
    }

Upvotes: 1

Gerald Versluis
Gerald Versluis

Reputation: 33993

Do you need an actual button? Else look at the TapGestureRecognizer. In this post is described how you can use it. You can apply it to virtually any control.

For example if you would style a Label to look like a button, you would add a double tap recognizer on it like this:

<Label Text="Tap me, I double dare you">
    <Label.GestureRecognizers>
        <TapGestureRecognizer
                Tapped="OnTapGestureRecognizerTapped"
                NumberOfTapsRequired="2" />
  </Label.GestureRecognizers>
</Label>

Of course you need to have an event called OnTapGestureRecognizerTapped in your code behind. But because of the value in the NumberOfTapsRequired property, you will need a double tap to activate it.

If you prefer code, this would be the counterpart:

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.NumberOfTapsRequired = 2;
tapGestureRecognizer.Tapped += (s, e) => {
    // handle the tap
};
label.GestureRecognizers.Add(tapGestureRecognizer);

Upvotes: 1

Related Questions