有没有办法可以自定义 Switch 颜色

2024-03-31

我的代码使用这样的标准开关:

<Switch HorizontalOptions="End" IsToggled="{Binding PbSwitch}" />

显示时,打开和关闭看起来像这样:

有没有办法进行自定义,以便我可以在 iOS 和 Android 中将开关的背景颜色设置为不同的颜色。我认为这需要一个自定义渲染器,但我不知道如何做到这一点。

提出的解决方案存在问题:


如果我清楚你想要什么,你可能需要自定义渲染器来实现这种效果。


首先,在PCL中定义一个带有颜色BindableProperty的CustomSwitch(通过它你可以设置值并在不同平台上使用)

自定义开关

public class CustomSwitch : Switch  
{  
   public static readonly BindableProperty SwitchOffColorProperty =  
     BindableProperty.Create(nameof(SwitchOffColor),  
         typeof(Color), typeof(CustomSwitch),  
         Color.Default);  

   public Color SwitchOffColor  
   {  
       get { return (Color)GetValue(SwitchOffColorProperty); }  
       set { SetValue(SwitchOffColorProperty, value); }  
   }  

   public static readonly BindableProperty SwitchOnColorProperty =  
     BindableProperty.Create(nameof(SwitchOnColor),  
         typeof(Color), typeof(CustomSwitch),  
         Color.Default);  

   public Color SwitchOnColor  
   {  
       get { return (Color)GetValue(SwitchOnColorProperty); }  
       set { SetValue(SwitchOnColorProperty, value); }  
   }  

   public static readonly BindableProperty SwitchThumbColorProperty =  
     BindableProperty.Create(nameof(SwitchThumbColor),  
         typeof(Color), typeof(CustomSwitch),  
         Color.Default);  

   public Color SwitchThumbColor  
   {  
       get { return (Color)GetValue(SwitchThumbColorProperty); }  
       set { SetValue(SwitchThumbColorProperty, value); }  
   }  

   public static readonly BindableProperty SwitchThumbImageProperty =  
     BindableProperty.Create(nameof(SwitchThumbImage),  
         typeof(string),  
         typeof(CustomSwitch),  
         string.Empty);  

   public string SwitchThumbImage  
   {  
       get { return (string)GetValue(SwitchThumbImageProperty); }  
       set { SetValue(SwitchThumbImageProperty, value); }  
   }  
} 

Android

[assembly: ExportRenderer(typeof(CustomSwitch), typeof(CustomSwitchRenderer))]
namespace FormsApp.Android
{
public class CustomSwitchRenderer : SwitchRenderer  
{  
    private CustomSwitch view;  
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Switch> e)  
    {  
        base.OnElementChanged(e);  
        if (e.OldElement != null || e.NewElement == null)  
            return;  
        view = (CustomSwitch)Element;  
        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean)  
        {  
            if (this.Control != null)  
            {  
                if (this.Control.Checked)  
                {  
                    this.Control.TrackDrawable.SetColorFilter(view.SwitchOnColor.ToAndroid(), PorterDuff.Mode.SrcAtop);  
                }  
                else  
                {  
                    this.Control.TrackDrawable.SetColorFilter(view.SwitchOffColor.ToAndroid(), PorterDuff.Mode.SrcAtop);  
                }  
               this.Control.CheckedChange += this.OnCheckedChange;  
                UpdateSwitchThumbImage(view);  
            }  
            //Control.TrackDrawable.SetColorFilter(view.SwitchBGColor.ToAndroid(), PorterDuff.Mode.Multiply);  
        }  
    }  
      
    private void UpdateSwitchThumbImage(CustomSwitch view)  
    {  
        if (!string.IsNullOrEmpty(view.SwitchThumbImage))  
        {  
            view.SwitchThumbImage = view.SwitchThumbImage.Replace(".jpg", "").Replace(".png", "");  
            int imgid = (int)typeof(Resource.Drawable).GetField(view.SwitchThumbImage).GetValue(null);  
            Control.SetThumbResource(Resource.Drawable.icon);  
        }  
        else  
        {  
            Control.ThumbDrawable.SetColorFilter(view.SwitchThumbColor.ToAndroid(), PorterDuff.Mode.Multiply);  
            // Control.SetTrackResource(Resource.Drawable.track);  
        }  
    }  

  private void OnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)  
    {  
        if (this.Control.Checked)  
        {  
            this.Control.TrackDrawable.SetColorFilter(view.SwitchOnColor.ToAndroid(), PorterDuff.Mode.SrcAtop);  
        }  
        else  
        {  
            this.Control.TrackDrawable.SetColorFilter(view.SwitchOffColor.ToAndroid(), PorterDuff.Mode.SrcAtop);  
        }  
    }  
    protected override void Dispose(bool disposing)  
    {  
        this.Control.CheckedChange -= this.OnCheckedChange;  
        base.Dispose(disposing);  
    }  
}  
}

iOS

[assembly: ExportRenderer(typeof(CustomSwitch), typeof(CustomSwitchRenderer))]
namespace FormsApp2.iOS
{
    class CustomSwitchRenderer : SwitchRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Switch> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null || e.NewElement == null)  return;

            CustomSwitch s = Element as CustomSwitch;

            UISwitch sw = new UISwitch();
            sw.ThumbTintColor = s.SwitchThumbColor.ToUIColor();
            sw.OnTintColor = s.SwitchOnColor.ToUIColor();

            SetNativeControl(sw);
        }
    }
}

便携式应用

<local:CustomSwitch Margin="50" SwitchOnColor="Red"/>

不要忘记在 Xml 中添加 xmlns(namespace)

xmlns:local = "clr-namespace:YouAppName"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法可以自定义 Switch 颜色 的相关文章

  • 添加UITabBarController并且没有NavigationController

    由于我是 Xamarin IOS 的新手 我想问一个问题 我已经关注了这个例子 https developer xamarin com guides ios user interface controls creating tabbed a
  • xamarin intellisense 无法在 Windows 10 上的 Visual Studio 2015 中工作

    我一直在尝试在 Windows 10 平台上将 Xamarin 与 Visual Studio 2015 一起使用 我无法对 XML 使用 Intellisense 这非常令人沮丧 有什么解决办法吗 您需要将 android 布局文件的 x
  • Xamarin Forms 可折叠 StackLayout

    我正在尝试实现一种可折叠的 StackLayout 每次用户单击该按钮时 它都会展开或折叠堆栈布局以显示 隐藏更多详细信息 我能够使用下面的代码实现更多 更少的效果 但它看起来不正确 效果也不是很好 因为它立即增长 并且我正在将效果应用到其
  • Xamarin 无法从异步获取实例

    我编写了一个通过蓝牙连接到 ESP32 的 Xamarin Forms 应用程序 现在我想从 MainPage xaml 页面的 CustomControl JoystickControl 获取值 我已经这样尝试过了 MainPage xa
  • 如何调试仅在发布模式下崩溃的 Android 应用程序

    在调试模式下一切正常 但在发布模式下崩溃 调试模式下有哪些所需权限在发布模式下未打开 EDIT 当我将 链接 设置为 无 时 我会通过第一个屏幕进入 登录 屏幕 但是 当我添加发布权限时Internet 第一次尝试读取远程实体框架核心表时它
  • 构建成功时,Intellisense 不断显示错误 Visual Studio 2015

    因此 我正在开发一个 Xamarin 项目 突然 Visual studio 2015 开始崩溃 它几乎在所有内容下都显示错误红线 例如 InitializeComponent 在每个页面中都有红线 项目构建和运行没有错误 错误仅来自 In
  • Xamarin 分步向导 Android 视图

    我想在 Xamarin c 中构建一个 android 活动 用于逐步注册和 或信息 我怎样才能做这样的事情 谁能给我一个代码示例或其他东西 谢谢 基本上你需要使用一个名为 a 的元素ViewPager 并且每个页面都会不同Fragment
  • Xamarin.Forms DataTemplateSelector 不适用于 iOS(未调用构造函数)

    我正在膨胀数据模板选择器 如下所示
  • 未选择为此解决方案配置构建项目

    错误 gt Skipped Deploy Project DrawShape Android Configuration Debug Any CPU gt Project not selected to build for this sol
  • 在 Xamarin 中隐藏软键盘

    如何隐藏软键盘以便在聚焦时显示Entry在 Xamarin forms 便携式表单项目中 我假设我们必须为此编写特定于平台的渲染器 但以下内容不起作用 我创建自己的条目子类 public class MyExtendedEntry Entr
  • 使用 Xamarin.Forms 和 Zxing 生成 QR 码

    我在网上看到了很多关于这个的内容 旧帖子 但似乎没有什么对我有用 我正在尝试从字符串中生成二维码并将其显示在应用程序中 这就是我一开始的情况 qrCode new ZXingBarcodeImageView BarcodeFormat Ba
  • Android - 正确使用 invalidateOptionsMenu()

    我一直在寻找很多invalidateOptionsMenu 我知道它的作用 但我想不出这种方法在现实生活中有用的任何例子 我的意思是 例如 假设我们要添加一个新的MenuItem to our ActionBar 我们可以简单地获取菜单on
  • 如何以编程方式检索 Visual Studio for Mac 的版本信息?

    我想在 Xamarin 应用程序的生成作业期间检索 Visual Studio for Mac 的版本信息 目标是将它们作为调试信息包含在二进制文件中 有没有办法以编程方式或使用 msbuild 的命令语句获取 Visual Studio
  • xamarin studio 中有包管理器控制台吗

    我正在使用 xamarin studio 带有 nuget 包管理插件 并且在我的项目中有一些 nuget 包 项目上下文菜单中有 管理 和 恢复 nuget 包 但也有控制台吗 Xamarin Studio 和 MonoDevelop 的
  • xaml UI 未以 xamarin 形式更新

    我将我的模型与我的 UI 绑定 在我的模型中 我做了一些计算 但其他属性与 UI 绑定 但我完成计算的某些属性不与我的 UI 绑定 而是在我的 OnPropertyChange 事件中显示计算 帮助我解决我的代码问题在哪里 提前致谢 我的模
  • 保护 APK 中的字符串

    我正在使用 Xamarin 的 Mono for Android 开发一个 Android 应用程序 我目前正在努力使用 Google Play API 添加应用内购买功能 为此 我需要从我的应用程序内向 Google 发送公共许可证密钥
  • 如何从代码隐藏中设置 CarouselView 的项目?

    我有一个 CarouselView 它绑定到图像的 ItemsSource 但我想通过更改 CarouselView 的索引来更改当前显示的图像 我尝试使用 CarouselView Position 作为必须选择的元素的索引 但不幸的是这
  • 使用 Xamarin Forms 显示图像

    Solved 答案是更新所有 nuget 软件包并针对较新版本的 Android 现在图像按预期加载 我对此并不满意 因为我完全使用了 Xamarin 提供的代码 并且针对较新的版本已弃用了代码所依赖的一些项目 初始版本是 Xamarin
  • 如何以xamarin形式使用消息中心

    我正在尝试使用消息中心而不是 xamarin 表单中的 Messenger 我不知道消息中心 我尝试使用以下代码以 xamarin 表单订阅和发送消息 MessagingCenter Send this TodoTable Todo 但我不
  • iOS App Store ExecutionEngineException 尝试 JIT 编译

    我有一个非常尴尬的问题 我已经为 iOS 构建了我的应用程序 并在所有模拟器上对其进行了测试 并且运行良好 我已将其安装在设备 iPhone 6 plus 上 效果也很好 然而 当我将其提交到应用商店时 反馈是它在所有设备上启动时都会崩溃

随机推荐