简体   繁体   中英

ANDROID - Jetpack Compose: how to implement theme settings?

I'm having hard times trying to implement a preference who switch the application theme.

Normally I would be able to do it with XML but with Jetpack Compose I saw that the best practice is to use DataStore ( https://developer.android.com/topic/libraries/architecture/datastore )

Someone please, can explain me from scratch how to store a preference and change the whole application theme when the user click on a button for example?

Thank you

I believe that the DataStore documentation already explains in great detail how it works...
Talking about Compose we have the isSystemInDarkTheme function which brings up the current theme of the user's android system (which can be seen in Theme.kt inside the ui package that Android Studio automatically creates in a Compose project).

What needs to be done is whenever you open the app, check if the user has chosen to change the theme manually in your app through a function that accesses the DataStore, in other words, provide a Flow<Boolean?> , with a logic like if null the user has not changed the theme on your app, so you follow with the android system and if have the boolean, pass and apply to the MaterialTheme of Compose.
And you also need to create a function that sends a boolean to the DataStore regarding the theme change on the app.

Here is a repository with example code allowing the user to change the theme between dark and light and saving the option in the DataStore. And here is an article with theoretical and practical explanation about themes in Compose which I think may contribute to the clarification.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM