Created
December 7, 2022 12:58
-
-
Save MrNtlu/c423c7d4867bf4f4edc25ae6fa2f8875 to your computer and use it in GitHub Desktop.
Jetpack Compose Dark Theme Main Activity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : ComponentActivity() { | |
private val themeViewModel: ThemeViewModel by viewModels() | |
private lateinit var dataStoreUtil: DataStoreUtil | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
dataStoreUtil = DataStoreUtil(applicationContext) | |
//Checks if the system theme is DarkMode or not. | |
val systemTheme = when (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) { | |
Configuration.UI_MODE_NIGHT_YES -> { true } | |
Configuration.UI_MODE_NIGHT_NO -> { false } | |
else -> { false } | |
} | |
setContent { | |
val theme = dataStoreUtil.getTheme(systemTheme).collectAsState(initial = systemTheme) | |
JetpackComposeDarkThemeTheme( | |
darkTheme = theme.value, | |
) { | |
Surface( | |
modifier = Modifier.fillMaxSize(), | |
color = MaterialTheme.colorScheme.background, | |
) { | |
DarkThemeScreen(dataStoreUtil, themeViewModel) | |
} | |
} | |
} | |
} | |
} | |
@OptIn(ExperimentalMaterial3Api::class) | |
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") | |
@Composable | |
fun DarkThemeScreen( | |
dataStoreUtil: DataStoreUtil, | |
themeViewModel: ThemeViewModel, | |
) { | |
var switchState by remember {themeViewModel.isDarkThemeEnabled } | |
val coroutineScope = rememberCoroutineScope() | |
Scaffold( | |
//... | |
) { | |
Column( | |
//... | |
) { | |
//... | |
Switch( | |
checked = switchState, | |
onCheckedChange = { | |
switchState = it | |
coroutineScope.launch { | |
dataStoreUtil.saveTheme(it) | |
} | |
}, | |
thumbContent = { | |
Icon( | |
modifier = Modifier | |
.size(SwitchDefaults.IconSize), | |
imageVector = if (switchState) Icons.Rounded.DarkMode else Icons.Rounded.LightMode, | |
contentDescription = "" | |
) | |
}, | |
colors = SwitchDefaults.colors( | |
checkedTrackColor = MaterialTheme.colorScheme.primary, | |
checkedThumbColor = MaterialTheme.colorScheme.onPrimary, | |
), | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment