nnsr nnsr - 3 months ago 127
Android Question

how to change default color when switch is "on"(blue to green) in forms xamarin. In ios default it is GReen but in android it is blue

wirth this code i am getting swith in blue color when it "on". i want to change it to green.

using Xamarin.Forms;

namespace swithcasedemo
{
public class MyPage : ContentPage
{
public MyPage ()
{
Content = new StackLayout {
Children = {
new Label { Text = "Hello ContentPage",
HorizontalOptions=LayoutOptions.Center,
VerticalOptions=LayoutOptions.CenterAndExpand
},
new Switch{
HorizontalOptions=LayoutOptions.Center,
VerticalOptions=LayoutOptions.CenterAndExpand,


},


}
};
}
}
}

Answer

This worked for me using Android >= 4.1

//need to reference Drawables otherwise StateListDrawable is not recognized.
using Android.Graphics.Drawables;

//...
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
       //...
       mySwitch = view.FindViewById<Switch>(Resource.Id.theSwitchIdFromXml);
       //... 

        Android.Graphics.Color colorOn = Android.Graphics.Color.Green;
        Android.Graphics.Color colorOff = Android.Graphics.Color.Brown;
        Android.Graphics.Color colorDisabled = Android.Graphics.Color.Gray;

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

        mySwitch.ThumbDrawable = drawable;
  }

The "default" state needs to be added as the last.

I Hope it will help.