iamthevoid
05/19/2021, 8:16 AMisSystemInDarkTheme()
sources [1]:
but when i try to change uiMode [2]
i get nothing [3]
If i open Configuration
sources i see that uiMode
just public int
so (theoretically) it must changes and reads as expected but it doesn’tZach Klippenstein (he/him) [MOD]
05/19/2021, 8:17 AMiamthevoid
05/19/2021, 8:18 AMZach Klippenstein (he/him) [MOD]
05/19/2021, 8:18 AMapply {}
function doesn’t actually do anything, it’s just syntactic sugar. Calling something.apply {}
is an expression that just returns something
– it doesn’t have any side effects.iamthevoid
05/19/2021, 8:19 AM@Composable
@ReadOnlyComposable
fun isSystemInDarkTheme(): Boolean {
val uiMode = LocalConfiguration.current.uiMode
return (uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
}
iamthevoid
05/19/2021, 8:19 AM@Composable
private fun setDarkTheme() {
LocalConfiguration.current.apply {
uiMode = uiMode or Configuration.UI_MODE_NIGHT_MASK
}
}
@Composable
private fun setLightTheme() {
LocalConfiguration.current.apply {
uiMode = uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()
}
}
iamthevoid
05/19/2021, 8:19 AMclass TypographyTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun testTypography() {
composeTestRule.setContent {
setLightTheme()
Assert.assertEquals(false, isSystemInDarkTheme())
setDarkTheme()
Assert.assertEquals(true, isSystemInDarkTheme()) // Assertion error
.........
cb
05/19/2021, 8:19 AMCompositionLocalProvider
to change a local value: https://developer.android.com/reference/kotlin/androidx/compose/runtime/package-summary#CompositionLocalProvider(kotlin.Array,kotlin.Function0)cb
05/19/2021, 8:21 AMiamthevoid
05/19/2021, 8:28 AMisSystemInDarkTheme()
directly if it possible, so i’ll try look to CompositionLocalProvider
iamthevoid
05/19/2021, 8:32 AMapply
do and try to change receiver’s (LocalConfiguration.current
) field in my snippet. It should work.Zach Klippenstein (he/him) [MOD]
05/19/2021, 8:34 AMa.value = 34
- apply
doesn’t actually do anything there except shift syntax aroundZach Klippenstein (he/him) [MOD]
05/19/2021, 8:35 AMConfiguration
, but because Configuration
isn’t aware of compose, changing its fields won’t trigger recomposition at all.Zach Klippenstein (he/him) [MOD]
05/19/2021, 8:36 AMCompositionLocalProvider
like Chris suggested. But that’s a lot of unnecessary work when you could just create a more explicit mechanism for selecting between light and dark themes.cb
05/19/2021, 8:41 AMAppCompatDelegate.setDefaultNightMode
) and assert that the resolved theme is light/dark.cb
05/19/2021, 8:41 AMiamthevoid
05/19/2021, 8:47 AMisSystemInDarkTheme()
. Tests placed in another (Typography) module. Typography uses colors and doesn’t aware about day-night theme. I try to check typography changes when system theme changes. There is no more simpler way to check it than mocking isSystemInDarkTheme
call (i quess)iamthevoid
05/19/2021, 8:53 AMcb
05/19/2021, 8:58 AM