C# – how to change the default color when the switch is set to “on” (blue to green) in the form xamarin. In IOS, it is green by default, but in Android, it is blue
•
Android
Wirth this code, when it "turns on", I'm using the blue switch. I want to turn it 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,
},
}
};
}
}
}
resolvent:
This applies to 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;
}
You need to add the "default" state as the last one
I hope it will help
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码