当前位置:首页 > 操作系统 > Ios

c# – 如何在表单xamarin中将开关设置为“on”(蓝色到绿色)时更改默认颜色.在ios默认它是GReen但在android中它是蓝色的

wirth这个代码当它“开启”时,我正在用蓝色开关.我想把它变成绿色.

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,


                    },


                }
            };
        }
    }
}

解决方法:

这适用于我使用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;
  }

需要添加“默认”状态作为最后一个.

我希望它会有所帮助.


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!