开发者

How do I automatically show different resources for light vs dark themes in Android?

开发者 https://www.devze.com 2023-01-27 13:36 出处:网络
As I understand, there are two built in themes for Android, Light and Dark. I want my application to display different resources based on which theme the user is using (NOT by having the user explicit

As I understand, there are two built in themes for Android, Light and Dark. I want my application to display different resources based on which theme the user is using (NOT by having the user explicitly specify a theme in my app!). Is 开发者_JAVA技巧this possible? If so, is it possible to do via xml resources, or is a programmatic approach required?

Note: Yes, I've read http://d.android.com/guide/topics/ui/themes.html at least thrice. It seems like all it tells me how to do is set one specific theme or styles to my element, rather than displaying light/dark elements correctly.


Yes, it can be done via XML resources.

From https://developer.android.com/preview/features/darktheme#themes_and_styles:

Your themes and styles should avoid hard-coded colors or icons intended for use under a light theme. You should use theme attributes (preferred) or night-qualified resources instead.

So yes, there are resource qualifiers for that, see https://developer.android.com/guide/topics/resources/providing-resources.html#NightQualifier : night and notnight suffixes.

I find Material theme website to be pretty good at explaining this but the most important part is:

Alternatively, if you want to define separate Light and Dark themes for your app, you can inherit from Theme.MaterialComponents.Light in the values directory, and Theme.MaterialComponents in the values-night directory. E.g.:

res/values/themes.xml

<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light">
    <!-- ... -->
</style>

res/values-night/themes.xml

<style name="Theme.MyApp" parent="Theme.MaterialComponents">
   <!-- ... -->
</style>


This is a site you can check for alternative drawable folders.

http://developer.android.com/guide/topics/resources/providing-resources.html

Also, this document might be helpful. http://developer.android.com/guide/topics/ui/themes.html

For regular themes: I'm not aware of any functions in Android about that, you might need to develop it yourself.

0

精彩评论

暂无评论...
验证码 换一张
取 消