如何在 Xamarin、Android 项目中设置主题、样式、颜色等,使其不受暗/亮模式的影响?

问题描述

我的主题/颜色设置...

应用程序.xaml:

<Application.Resources>
        <Color x:Key="PageBackgroundColor">#1F1F1F</Color>
        <Style targettype="Entry">
            <Setter Property="HorizontalOptions" Value="Fill" />
            <Setter Property="TextColor" Value="Whitesmoke" />
            <Setter Property="PlaceholderColor" Value="Red" />
            <Setter Property="HorizontalTextAlignment" Value="Center" />
        </Style>
        <Style targettype="Label">
            <Setter Property="TextColor" Value="WhiteSmoke" />
        </Style>
        <Style targettype="TimePicker">
            <Setter Property="TextColor" Value="WhiteSmoke" />
        </Style>
        <Style targettype="Picker">
            <Setter Property="TextColor" Value="WhiteSmoke" />
            <Setter Property="TitleColor" Value="Red" />
        </Style>
    </Application.Resources>    

styles.xml:

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <style name="MainTheme" parent="MainTheme.Base">  
    <item name="colorAccent">#ff0000</item>    
  </style>
  <style name="MainTheme.Base" parent="Theme.AppCompat.Light">
    <item name="android:timePickerDialogTheme">@style/MyTimePickerDialogStyle</item>
  </style>
  <style name="MyTimePickerDialogStyle" parent="@style/ThemeOverlay.AppCompat.Dialog.Alert">
    <item name="colorControlActivated">#FF0000</item>
    <item name="colorAccent">#000000</item>
    <item name="android:textColorPrimary">#000000</item>
    <item name="android:textColorSecondary">#000000</item>
  </style>     
</resources>

MainPage.xaml:

<ContentPage ...
             BackgroundColor="{DynamicResource PageBackgroundColor}"
             ...>
    ...
    <Button ... TextColor="#F5F5F5" BackgroundColor="#007F00" ... />
    ...
    <Label ... BackgroundColor="#F5F5F5" ... />

无论选择何种深色/浅色模式,我的应用都应位于深色背景上。暗/亮模式不应影响任何颜色。 Android 10 上的 Light 模式没有颜色问题。 使用深色模式

  • 按钮绿色 (#008000) 变成石灰,这使得白色文本颜色不可读,所以我不得不将按钮背景颜色属性从绿色 (#008000) 更改为 #007F00,尽管两者之间存在差异,但效果出奇地正常颜色很少
  • 标签 WhiteSmoke (#F5F5F5) 变暗
  • 如果我将 <Setter Property="TextColor" Value="WhiteSmoke" /> 更改为 <Setter Property="BackgroundColorColor" Value="WhiteSmoke" />,更改将仅适用于浅色主题
  • 将背景颜色设置为红色 (#FF0000) 的按钮没有问题

为什么黑暗模式只影响某些颜色?我想有一些设置可以覆盖暗模式。有什么建议吗?

编辑:有没有办法停用黑暗模式? 如何设置主题、样式、颜色等,使其不受深色/浅色模式的影响?

EDIT2:截图...

灯光模式:

White mode

深色模式

Dark mode

EDIT3:它也会影响图像。

我尝试了两个几乎相同的图像,唯一的区别是红色和绿色背景。背景的其余部分是透明的。 “swipe”这个词和箭头是#F5F5F5颜色,而“A”周围的圆圈是#FFFFFF。图片来自 Photoshop:

swipe_colours

swipe_white

白/暗模式下的截图:

White_mode

___

White_mode

如您所见,与我之前提到的十六进制颜色类似,暗模式仅影响两个图像中的一个

解决方法

根据document,您可以Set the current user theme

应用程序使用的主题可以通过 Application.UserAppTheme 属性,属于 OSAppTheme 类型, 无论当前运行的是哪个系统主题:

Application.Current.UserAppTheme = OSAppTheme.Dark;

您也可以设置相同的颜色under light/dark mode

<Label Text="This text is green in light mode,and green in dark mode."
               TextColor="{AppThemeBinding Light=Green,Dark=Green}" />