Hi, I have a question regarding using color resour...
# glance
j
Hi, I have a question regarding using color resources in glance. In some cases, it is not possible (or I haven't found a way) to use a color resource - for example to set the color of Text, because color of
TextStyle
is of type
ColorProvider
and the factory function to create
ColorProvider
from resource is restricted to the library and says
Returns a [ColorProvider] that resolves to the color resource. This should not be used outside of the Glance Libraries due to inconsistencies with regards to what process (app vs launcher) colors are resolved in
That's also the case with
colorFilter
for
Image
, color of
CircularProgressIndicator
and probably more. On the other hand, there's a
.background
modifier that accepts color resource and is working just fine. I tried to overcome this by using
RemoteViews
directly, so for example I can set the color of Text like this:
Copy code
AndroidRemoteViews(
    remoteViews = RemoteViews(context.packageName, R.layout.widget_textview).apply {
        setTextViewText(R.id.text, text)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            setTextViewTextColorResource(R.id.text, colorRes)
        } else {
            setTextColor(R.id.text, LocalContext.current.getColor(colorRes))
        }
    },
)
and this seems to be working fine too. After all, the glance theme's dynamic colors are also created from resources... So, what's the reason for that restriction of
ColorProvider
? And can my approach with remote views cause troubles in some cases (not resolving to correct color)?
b
Sorry in the delay getting back to you. The issue we've seen is that it's easy to make mistakes when dealing directly with color resources in glance. The reason is that there's a couple of things that can change. • Light/Dark theme • Dynamic colors. In particular, if there's scenarios where some colors get resolved in the appwidget's process, but other colors get resolved in the launcher, there can be discrepancies. In the example you gave,
setTextColor(R.id.text, LocalContext.current.getColor(colorRes))
runs the risk of not updating if the appwidget's host (launcher most likely) switches from light to dark mode. Anything that is using GlanceTheme or resources in the remoteviews will update, but anything that's hardcoded wont. There's a couple guidelines for using color. • Create a GlanceTheme • Don't use resource defined colors, either use dynamic color, or hard code light and dark color values for each of your tokens in the app and give them to a `ColorProvider(day=..., night=...) You can see some examples of working with color in our demos directory, and in particular, the demos subproject https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:glance/g[…]on-tests/demos/src/main/java/androidx/glance/appwidget/demos/
w
Is there a way to implement GlanceTheme with light and dark modes on Android SDK <= 30 or should I use RemoteViews?