2016-05-16 48 views
1

我想通了。 對於任何需要此功能的人。請參閱以下內容。 看了Xamarin Evolve一百萬次我就抓住了。如何使用Xamarin Forms自定義按鈕渲染器的觸摸事件來更改按鈕圖片

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

別忘了'thisButton.Touch - = ...'否則你會有一些內存泄漏 –

+0

謝謝。我忘了那個。 –

+0

我們什麼時候該做'thisButton.Touch - = ...'? –

回答

0

你需要調用

Control.CallOnClick();

0

下面是一個示例如何實現Xamarin形式兩個狀態的ImageButton:

PCL:

public class FancyButton : Button 
{ 
    public void SendClickedCommand() 
    { 
     ICommand command = this.Command; 
     if (command != null) 
     { 
      command.Execute(this.CommandParameter); 
     } 
    } 
} 

Android的渲染:

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); 
    } 
} 

注:在觸摸事件集: e.Handled = false;導致Click事件上升。