Search code examples
xamarintouchmvvmcrossontouch

How to create an "ontouch" event for my button in xamarin mvvmcross?


In my project I'm trying to create an audio button like the one that uses whatsap that when you keep pressed start recording and when you put down stop recording.I found solutions where he uses 2 buttons, one to start and one to finish. what I need is that with the same button when pressing and releasing, I execute my code. I did not find any implementation of the event I'm trying to capture. Could you help me with this? this is my button in the axml file

 <android.support.design.widget.FloatingActionButton
                android:id="@+id/btn_record"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom|right"
                android:src="@drawable/ic_micro"
                android:layout_marginRight="15dp"
                android:layout_marginBottom="15dp"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:theme="@style/ControlsTheme"
                local:MvxBind="Click RecordAudioClick; Visibility Visibility(RecordAudioVisibility); Touch Touch" />

this is my code in the viewmodel

  public MvxCommand Touch
    {
        get
        {
            return new MvxCommand(() =>
            {
                UserDialogs.Instance.Toast(new ToastConfig(Pressed Button")
                 .SetDuration(3000)
                 .SetMessageTextColor(System.Drawing.Color.White)
                 .SetBackgroundColor(System.Drawing.Color.Black)
                 .SetPosition(ToastPosition.Top));
            });
        }
    }

Solution

  • On Android you can subscribe to the Touch event:

    button.Touch += OnButtonTouch;
    
    private void OnButtonTouch(object sender, View.TouchEventArgs args)
    {
        var handled = false;
        if (args.Event.Action == MotionEventActions.Down)
        {
            // do stuff when pressed
            handled = true;
        }
        else if (args.Event.Action == MotionEventActions.Cancel ||
                 args.Event.Action == MotionEventActions.Up)
        {
            // do stuff when released
            handled = true;
        }
    
        args.Handled = handled;
    }
    

    On iOS this code is kind of similar:

    button.TouchDown += OnButtonTouchDown;
    button.TouchUpInside += OnButtonTouchUpInside;
    
    private void OnButtonTouchDown(object sender, EventArgs e)
    {
        // do stuff when pressed
    }
    
    private void OnButtonTouchUpInside(object sender, EventArgs e)
    {
        // do stuff when released
    }