Reputation: 31
I want to change the color of switch in android and created custom renderer just like as one of the post from stack overflow: Below is the code
public class CustomSwitchRenderer : SwitchRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Switch> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.TextOn = "Yes";
Control.TextOff = "No";
Android.Graphics.Color colorOn = Android.Graphics.Color.Rgb(239, 201, 6);
Android.Graphics.Color colorOff = Android.Graphics.Color.LightGray;
Android.Graphics.Color colorDisabled = Android.Graphics.Color.Gray;
Android.Graphics.Color textColor = Android.Graphics.Color.Black;
Control.SetTextColor (ColorStateList.ValueOf (textColor));
Control.SetTextColor (textColor);
StateListDrawable drawable = new StateListDrawable();
drawable.AddState(new int[] { Android.Resource.Attribute.StateChecked }, new ColorDrawable(colorOn));
drawable.AddState(new int[] { -Android.Resource.Attribute.StateEnabled }, new ColorDrawable(colorDisabled));
drawable.AddState(new int[] { }, new ColorDrawable(colorOff));
Control.ThumbDrawable = drawable;
}
}
} This code isn't working for me ? Do i need to add some items in drawable folder as well ?
Upvotes: 1
Views: 5506
Reputation: 7552
For Android you can change the propery "colorAccent" on your "styles.xml" file
<item name="colorAccent">#008000</item>
Upvotes: 0
Reputation: 1175
With Forms 2.1, there are now effects which can remove the need for a custom renderer in situations where only minor visual changes are being made. See the linked guide for getting started on using them.
Upvotes: 2
Reputation: 1817
You can create your own control in your UI project:
public class MySwitch : Switch
{
}
After that change your forms where you used Switch
control to MySwitch
control.
And then you need to tell Xamarin.Forms
infrastructure that you are providing renderer for MySwitch
control.
In your *.Droid
project add following attribute at assembly level (above your namespace declaration or in AssemblyInfo.cs
file)
[assembly: ExportRenderer(typeof(MySwitch), typeof(CustomSwitchRenderer))]
Upvotes: 1