This page includes details for optional widget enhancements that are available starting in Android 12 (API level 31). These features are optional, but they're straightforward to implement and improve your users' widget experience.
Use dynamic colors
Starting in Android 12, a widget can use the device theme colors for buttons, backgrounds, and other components. This provides smoother transitions and consistency across different widgets.
There are two ways to achieve dynamic colors:
Use the system's default theme (
@android:style/Theme.DeviceDefault.DayNight
) in the root layout.Use the Material 3 theme (
Theme.Material3.DynamicColors.DayNight
) from the Material Components for Android library, available starting in Material Components for Android v1.6.0.
Once the theme is set in the root layout, you can use common color attributes in the root or any of its children to pick up the dynamic colors.
Some examples of color attributes you can use are the following:
?attr/primary
?attr/primaryContainer
?attr/onPrimary
?attr/onPrimaryContainer
In the following example using the Material 3 theme, the device's theme color is "purplish." The accent color and widget background adapt for light and dark modes, as shown in figures 1 and 2.
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/colorPrimaryContainer"
android:theme="@style/Theme.Material3.DynamicColors.DayNight">
...
app:tint="?attr/colorPrimaryContainer"
android:src="@drawable/ic_partly_cloudy" />


Backward compatibility for dynamic colors
Dynamic colors are only available in devices running Android 12
or higher. To provide a custom theme for lower versions, create a default theme
with your custom colors and a new qualifier (values-v31
) using the default
theme attributes.
Here is an example using the Material 3 theme:
/values/styles.xml
/values-v31/styles.xml