c# - xamarin.forms 中开关为 "on"(蓝色到绿色)时如何更改默认颜色在 ios 中默认为绿色,但在 android 中为蓝色

标签 c# android xamarin xamarin.android xamarin.forms

当它“打开”时,我得到的代码是蓝色的。我想把它改成绿色。

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

“默认”状态需要作为最后添加。

希望对您有所帮助。

关于c# - xamarin.forms 中开关为 "on"(蓝色到绿色)时如何更改默认颜色在 ios 中默认为绿色,但在 android 中为蓝色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28672625/

相关文章:

c# - Selenium WebDriver : unable to locate element (C#)

c# - 在 PCL 和 Windows Phone 应用程序中实现异步作用域

android - 无法通过android上的访问 token 获取Facebook Graph API信息

Xamarin.Forms,如何使用我当前的 Xamarin.Forms 找到兼容版本的 Android 支持库

c# - 输入 key 问题

c# - 如何创建元素自动实例化数组,例如用户自定义类型的int数组?

android - 我的 Android 小部件被杀死, "No longer want bellander.andro...."

android - 限制父边界内的 subview

ios - 是否可以在测试的iPhone上安装我的App

android - Android内存转储中的EGL和GL mtrack是什么