Button Long Press Programmatically

WillBellWillBell USMember ✭✭

Hello,

I am finding it difficult trying to track down info on implementing a Long Press Button Event using Xamarin Forms.

I have been messing around with XLabs but can't seem to get anything to work. Has anyone got any code of how to implement a long click listener on a button programmatically?

Much appreciated

Best Answer

Answers

  • NickKovalskyNickKovalsky USMember ✭✭✭

    Seems like you have to create your own derived button class, then looks at https://github.com/twintechs/TwinTechsFormsLib they have code for long press etc

  • WillBellWillBell USMember ✭✭

    I have started using TwinTechs. I get an error on the GestureRecognizerExtensions.cs when trying to use the Factory Variable.

    Above the Factory Variable it says 'Set this property by whatever means you have for IOC.

    What does this mean and how can I set Factory? Anyone got any code examples?

    Thanks

  • WillBellWillBell USMember ✭✭

    I have now got it working on labels, however I can't use it on Buttons.

    How can I get it working on buttons?

  • OrlinPerfanovOrlinPerfanov USMember

    My approach, please comment:
    1. Create ICustomButton interface in Forms

    namespace TestProject
    {
        interface ICustomButton
        {
        }
    }
    
    1. Create CustomButton in .Droid

          [assembly: Xamarin.Forms.Dependency(typeof(CustomButton))]
          namespace TestProject.Droid
          {
              [ContentProperty("CustomButton")]
          public class CustomButton : Button, ICustomButton
                  {
                      public Command LongPressCommand { get; set; }
              }
          }
      
    2. Create CustomButtonRenderer in .Droid

      [assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
      namespace TestProject.Droid
      {
          public class CustomButtonRenderer : Xamarin.Forms.Platform.Android.ButtonRenderer
          {
              protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
              {
                  base.OnElementChanged(e);
      
                  var view = (CustomButton)Element;
      
                  this.Control.LongClick += (s, args) =>
                  {
                      view.LongPressCommand.Execute(new object());
                  };
              }
          }
      }
      
    3. In XAML you can create the button as: <droid:CustomButton x:Name = "btnCustomButton"/>
      Or in c#: var btnCustomButton = DependencyService.Get<CustomButton>();

    4. Finally to set the command for the long press:

          var cmd = new Command(() =>
                   {
                       //// Whatever you have in mind ////
                   });
          btnCustomButton.LongPressCommand = cmd;
      
Sign In or Register to comment.