C# 开关为“时如何更改默认颜色”;关于;(蓝色到绿色)以沙马林的形式。在ios中默认为绿色,但在android中为蓝色
在这个代码中,当它“打开”时,我得到了蓝色的开关。我想把它换成绿色C# 开关为“时如何更改默认颜色”;关于;(蓝色到绿色)以沙马林的形式。在ios中默认为绿色,但在android中为蓝色,c#,android,xamarin,xamarin.android,xamarin.forms,C#,Android,Xamarin,Xamarin.android,Xamarin.forms,在这个代码中,当它“打开”时,我得到了蓝色的开关。我想把它换成绿色 using Xamarin.Forms; namespace swithcasedemo { public class MyPage : ContentPage { public MyPage () { Content = new StackLayout { Children = {
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,
},
}
};
}
}
}
这对我使用安卓>=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;
}
//需要引用Drawable,否则无法识别StateListDrawable。
使用Android.Graphics.Drawables;
//...
创建视图上的公共覆盖视图(布局、充气机、视图组容器、捆绑包保存状态)
{
//...
mySwitch=view.findviewbyd(Resource.Id.theSwitchIdFromXml);
//...
Android.Graphics.colorOn=Android.Graphics.Color.Green;
Android.Graphics.colorOff=Android.Graphics.Color.Brown;
Android.Graphics.colorDisabled=Android.Graphics.Color.Gray;
StateListDrawable drawable=新StateListDrawable();
AddState(新的int[]{Android.Resource.Attribute.StateChecked},新的ColorDrawable(colorOn));
AddState(新的int[]{-Android.Resource.Attribute.statenabled},新的ColorDrawable(colorDisabled));
AddState(新的int[]{},新的ColorDrawable(colorOff));
mySwitch.ThumbDrawable=可绘制;
}
“默认”状态需要添加为最后一个
我希望这会有所帮助。对于您在Xamarin上的IOS项目,您只需将这一行放到AppDelegate.cs的FinishedLaunching方法中即可
UISwitch.Appearance.OnTintColor = Color.FromHex("#yourColor").ToUIColor();
嗨,我也想这样做,但对于API 15(4.0.3–4.0.4)。你有办法做到这一点。或者在API 15中不可能这样做。您可以检查您使用的API中未包含的任何内容是否具有来自Compat库的等效内容。