androidandroid-dark-theme

Use a different image if Dark Mode is enabled on Android


I have two variants of a PNG, one where the drawn text is black and one where it is white. By default, on a white background, I am using the black image variant, but when the system dark mode is enabled the image becomes nearly invisible against the background.

How can I instruct my app to use the alternate image when dark mode is enabled?

The image is set in the activity's 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" />

Solution

  • I solved this with the following process:

    1. Create a new directory at app/src/main/res/drawable-night, mimicking the already existing path at app/src/main/res/drawable.
    2. Move the white variant image into the new drawable-night directory, changing the name from logo_white.png to logo.png.
    3. Rename the black variant image in the standard drawable directory from logo_black.png to logo.png
    4. Update the ImageView drawable reference from @drawable/logo_black to @drawable/logo

    It appears that Android recognizes the night variant directory and flips accordingly. Very nice :)