Xamarin 表单 - 设置切换文本颜色

Xamarin forms - set switch text color

如何在 android 渲染器中设置文本的颜色?我有以下渲染器:

public class CustomSwitchRenderer : SwitchRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Switch> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            Control.TextOn = "Yes";
            Control.TextOff = "No";

            Android.Graphics.Color colorOn = Android.Graphics.Color.Rgb(239, 201, 6);
            Android.Graphics.Color colorOff = Android.Graphics.Color.LightGray;
            Android.Graphics.Color colorDisabled = Android.Graphics.Color.Gray;
            Android.Graphics.Color textColor = Android.Graphics.Color.Black;

            Control.SetTextColor (ColorStateList.ValueOf  (textColor));
            Control.SetTextColor (textColor);

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

            Control.ThumbDrawable = drawable;

        }
    }
}

我可以更改开关的颜色,但我不知道如何更改 YES/NO 文本的颜色。 SetTextColor 似乎不起作用。

在您的 droid 项目的 Resources\values 目录下创建一个 xml 文件。 名称无关紧要,但它需要以 .xml 结尾并包含

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
        <item name="android:textColor">#00FF00</item>
    </style>
</resources>

然后在您的渲染器中调用 Control.SetSwitchTextAppearance。传入您创建的资源的 Context 和 ResId。您可以从标题为 Resource.designer.cs 的资源下生成的文件中获取 ID。或者,您可以调用如下生成的 Const。

Control.SetSwitchTextAppearance (Control.Context, Resource.Style.CodeFont);

希望对您有所帮助。如果你不能得到它让我知道我会上传一个示例应用程序。