We developing home screen widgets in 2021 and I tried to implement dark theme support.
According to https://developer.android.com/guide/topics/ui/look-and-feel/darktheme#widgets
"... use appropriate theme attributes instead of hardcoded colors."
So as I understand I can use custom attributes and I added attrs.xml in values folder
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="customBackgroundColor" format="color" />
</resources>
After that I added my custom attribute to light/dark theme
values/themes.xml
<resources>
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
<item name="customBackgroundColor">@color/white</item>
</style>
</resources>
And also for dark
values-night/themes.xml
<resources>
<style name="AppTheme" parent="Theme.MaterialComponents">
<item name="customBackgroundColor">@color/black</item>
</style>
</resources>
Here is my widget layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/customBackgroundColor" />
When I placing widget on home screen I got "Problem loading widget" message.
When I tried to hardcode colors for layouts, everything works as expected.
I also tried using default attributes "colorPrimary" and there was no error message but widget not changing color according to theme I switched.
Do I missing something or information in official docs is incorrect?