Build a Light/Dark Theme Toggle with Jetpack Compose in Android: A Step-by-Step Guide

Build a Light/Dark Theme Toggle with Jetpack Compose in Android: A Step-by-Step Guide

Easily switch between light and dark themes in your Android app with Jetpack Compose

One of the features that can elevate your app is the ability to switch between light and dark themes from within the app. In this tutorial, we'll show you how to create a theme toggle in Android using Jetpack Compose.

First, let's start by setting up our project for Jetpack Compose. If you're new to Jetpack Compose, you can check out the official documentation for more information on getting started.

Next, let's create a Theme.kt file to hold our theme state. This file will be responsible for storing the current theme and providing a method for toggling between the light and dark themes.

data class ThemeState(var theme: Theme) {
    fun toggleTheme() {
        theme = if (theme == Theme.Light) Theme.Dark else Theme.Light
    }
}

enum class Theme {
    Light, Dark
}

Now that we have our theme state set up, let's create a button that will allow us to toggle between the light and dark themes. We'll use the @Composable annotation to define a function that will be responsible for rendering the button.

@Composable
fun ToggleThemeButton() {
    val themeState = remember { ThemeState(Theme.Light) }
    Button(onClick = { themeState.toggleTheme() }) {
        Text("Toggle Theme")
    }
}

Finally, we'll need to apply the current theme to our app. We can do this by wrapping our app's content in a MaterialTheme component and setting the theme attribute based on the current value of our ThemeState.

@Composable
fun App() {
    val themeState = remember { ThemeState(Theme.Light) }
    MaterialTheme(
        theme = if (themeState.theme == Theme.Light) lightTheme else darkTheme
    ) {
        // app content goes here
    }
}

That's it! With these steps, you should now have a working light/dark theme toggle in your Android app using Jetpack Compose. You can customize the theme and the toggle button to fit the needs of your app.


I hope this article helps you build a light/dark theme toggle with Jetpack Compose in Android. Let me know if you have any questions or need further clarification on any of the steps.