如果在 Android 上启用深色模式,请使用不同的图像

Use a different image if Dark Mode is enabled on Android

我有两种 PNG 变体,一种绘制的文本是黑色的,另一种是白色的。默认情况下,在白色背景上,我使用的是黑色图像变体,但是当启用系统黑暗模式时,图像在背景中几乎看不见。

我如何指示我的应用程序在启用深色模式时使用备用图像?

图片设置在activity的XML:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.me.some_app.someActivity">

    <ImageView
        android:id="@+id/Logo"
        android:layout_width="176dp"
        android:layout_height="219dp"
        android:contentDescription="@string/LogoDescription"
        app:layout_constraintBottom_toTopOf="@+id/divider"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/logo_black" />

我通过以下过程解决了这个问题:

  1. app/src/main/res/drawable-night 中创建一个新目录,模仿 app/src/main/res/drawable 中已有的路径。
  2. 将白色变体图像移动到新的 drawable-night 目录中,将名称从 logo_white.png 更改为 logo.png
  3. 将标准 drawable 目录中的黑色变体图像从 logo_black.png 重命名为 logo.png
  4. ImageView 可绘制对象引用从 @drawable/logo_black 更新为 @drawable/logo

看来Android识别了夜间变体目录并相应地翻转。 非常好:)

您可以使用以下步骤:

1).从 左侧栏 查看 > 工具 Windows > 资源管理器 转到资源管理器


2). Select 可绘制选项卡(如果未 selected )



3).单击 “+” 图标和 select 导入可绘制对象



4). Select 文件并单击 确定



5).将两个文件重命名为相同的名称。 baseline_feedback_20 在我的例子中(暂时忽略警告)


6).单击添加另一个限定符,select 夜间模式,灯光模式的值为白天,然后深色模式的夜间

您可以阅读更多关于预选赛的内容here



7).单击 下一步,然后单击 导入,您就完成了。

在我的例子中,您可以照常使用资源 @drawable/logo@drawable/baseline_feedback_20,系统将按照 selected 模式获取文件。

我有一个简单的解决方案,你只需要一组图像,颜色无关紧要,在你将使用图像的组件上设置以下属性:

android:tint="@color/you_desired_color" 或 app:tint="@color/you_desired_color" 取决于组件。

例如

<ImageView
        android:id="@+id/icon"
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:tint="@color/you_desired_color" />

在res文件夹中你需要有以下文件夹 值和 values-night,每个值都有各自的 themes.xml 和 colors.xml