Tanaka
11/02/2021, 5:09 PM@AndroidEntryPoint
class MainActivity : ComponentActivity() {
val dataTwo = MutableLiveData<Boolean>(false)
@ExperimentalAnimationApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MainApp()
}
observeThemeState()
}
@ExperimentalAnimationApi
@Composable
fun MainApp() {
val darkMode by dataTwo.observeAsState(initial = false)
val toggleTheme: () -> Unit = {
dataTwo.value = !dataTwo.value!!
}
FastNewsTheme(darkTheme = darkMode) {
Surface(color = MaterialTheme.colors.background) {
UpdateStatusBarColor()
NavigationComponent(toggleTheme)
}
}
}
private fun observeThemeState(){
dataTwo.observe(this, {
val mode = when(it){
true -> AppCompatDelegate.MODE_NIGHT_YES
false -> AppCompatDelegate.MODE_NIGHT_NO
}
Log.d(TAG, "observeThemeState: $mode")
AppCompatDelegate.setDefaultNightMode(mode)
})
}
companion object {
const val TAG = "MainActivity"
}
}
@ExperimentalAnimationApi
@Composable
fun NavigationComponent(toggleTheme: () -> Unit) {
var navController = rememberAnimatedNavController()
AnimatedNavHost(navController = navController, startDestination = "main") {
composable("main",
exitTransition = { initial, target ->
if (initial.destination.id != target.destination.id) {
slideOutOfContainer(
AnimatedContentScope.SlideDirection.Left,
animationSpec = tween(2000)
)
} else {
null
}
},
enterTransition = { initial, target ->
if (initial.destination.id != target.destination.id) {
slideIntoContainer(
AnimatedContentScope.SlideDirection.Right,
animationSpec = tween(2000)
)
} else {
null
}
}
) {
MainScreen(navController, toggleTheme)
}
}
}
@ExperimentalAnimationApi
@Composable
fun MainScreen(
navController: NavController = rememberAnimatedNavController(),
toggleTheme: () -> Unit
) {
Scaffold(
topBar = {
TopAppBar(
title = {
Text("My App", style = MaterialTheme.typography.h2)
},
actions = {
IconButton(onClick = { toggleTheme() }) {
Icon(
painterResource(id = R.drawable.ic_baseline_light_mode_24),
contentDescription = null
)
}
}
)
}
) {
}
}