问题
I figured it out. For anyone needing this. Please see the following. After Watching Xamarin Evolve a million times I caught on.
class LoginButtonCustomRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
Android.Widget.Button thisButton = Control as Android.Widget.Button;
thisButton.Touch += (object sender, TouchEventArgs e2) =>
{
if (e2.Event.Action == MotionEventActions.Down)
{
System.Diagnostics.Debug.WriteLine("TouchDownEvent");
// Had to use the e.NewElement
e.NewElement.Image = "pressed.png";
}
else if (e2.Event.Action == MotionEventActions.Up)
{
System.Diagnostics.Debug.WriteLine("TouchUpEvent");
}
};
}
}
回答1:
you need call
Control.CallOnClick();
回答2:
Here is a sample how to implement a two state ImageButton in Xamarin Forms:
PCL:
public class FancyButton : Button
{
public void SendClickedCommand()
{
ICommand command = this.Command;
if (command != null)
{
command.Execute(this.CommandParameter);
}
}
}
Android render:
public class FancyButtonAndroid : ButtonRenderer
{
Android.Widget.Button thisButton;
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
thisButton = Control as Android.Widget.Button;
thisButton.SetBackgroundResource(Resource.Drawable.btn_unpress);
thisButton.Touch += ThisButton_Touch;
thisButton.Click += HandleButtonClicked;
}
private void ThisButton_Touch(object sender, TouchEventArgs e)
{
e.Handled = false;
if (e.Event.Action == MotionEventActions.Down)
{
System.Diagnostics.Debug.WriteLine("TouchDownEvent");
thisButton.SetBackgroundResource(Resource.Drawable.btn_press);
}
else if (e.Event.Action == MotionEventActions.Up)
{
System.Diagnostics.Debug.WriteLine("TouchUpEvent");
thisButton.SetBackgroundResource(Resource.Drawable.btn_unpress);
}
}
private void HandleButtonClicked(object sender, EventArgs e)
{
if (Element != null && Element is FancyButton)
{
(Element as FancyButton).SendClickedCommand();
}
}
protected override void Dispose(bool disposing)
{
if (thisButton != null)
{
thisButton.Touch -= ThisButton_Touch;
thisButton.Click -= HandleButtonClicked;
}
base.Dispose(disposing);
}
}
Note: in the Touch event set: e.Handled = false;
to cause the Click event to rise.
来源:https://stackoverflow.com/questions/37255469/how-to-use-xamarin-forms-custom-button-renderers-touch-event-to-change-the-butt