1 using Android.Graphics; 2 using Android.Widget; 3 using DCMS.Client.Droid.Renderer; 4 using Xamarin.Forms; 5 using Xamarin.Forms.Platform.Android; 6 7 [assembly: ExportRenderer(typeof(Xamarin.Forms.Switch), typeof(CustomSwitchRenderer))] 8 namespace DCMS.Client.Droid.Renderer 9 { 10 public class CustomSwitchRenderer : SwitchRenderer 11 { 12 private Xamarin.Forms.Switch view; 13 14 public CustomSwitchRenderer(Android.Content.Context context) : base(context) { } 15 16 protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Switch> e) 17 { 18 //this.Element.Toggled += this.OnElementToggled; 19 20 base.OnElementChanged(e); 21 if (e.OldElement != null || e.NewElement == null) 22 return; 23 24 //if (e.OldElement != null) 25 // e.OldElement.Toggled -= OnElementToggled; 26 27 //e.NewElement.Toggled += OnElementToggled; 28 29 view = (Xamarin.Forms.Switch)Element; 30 if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean) 31 { 32 if (Control != null) 33 { 34 if (this.Control.Checked) 35 { 36 this.Control.TrackDrawable.SetColorFilter(Xamarin.Forms.Color.FromHex("#6decacec").ToAndroid(), PorterDuff.Mode.SrcAtop); 37 } 38 else 39 { 40 this.Control.TrackDrawable.SetColorFilter(Xamarin.Forms.Color.FromHex("#6db3b1b3").ToAndroid(), PorterDuff.Mode.SrcAtop); 41 } 42 this.Control.CheckedChange += this.OnCheckedChange; 43 Control.SetTrackResource(Resource.Drawable.track); 44 } 45 } 46 } 47 48 private void OnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) 49 { 50 if (this.Control.Checked) 51 { 52 this.Control.TrackDrawable.SetColorFilter(Xamarin.Forms.Color.FromHex("#6decacec").ToAndroid(), PorterDuff.Mode.SrcAtop); 53 } 54 else 55 { 56 this.Control.TrackDrawable.SetColorFilter(Xamarin.Forms.Color.FromHex("#6db3b1b3").ToAndroid(), PorterDuff.Mode.SrcAtop); 57 } 58 Element.IsToggled = Control.Checked; 59 } 60 61 protected override void Dispose(bool disposing) 62 { 63 this.Control.CheckedChange -= this.OnCheckedChange; 64 base.Dispose(disposing); 65 } 66 67 } 68 }
效果以下:ide