我已经实现了自定义主题模式而不是选择系统主题,现在我无法为我的自定义主题实现启动屏幕。 我想检查我的首选项中的值,然后将更改应用到splash api。
@Inject
lateinit var splashViewModel: SplashViewModel
@RequiresApi(Build.VERSION_CODES.S)
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen().setKeepOnScreenCondition {
if (splashViewModel.isDarkMode.value){
splashScreen.setSplashScreenTheme(R.style.SplashScreenTheme) }
splashViewModel.isLoading.value
}
super.onCreate(savedInstanceState)
setContent {
val userViewModel: UserViewModel = viewModel()
val isDarkTheme = userViewModel.getSavedTheme().collectAsState(initial = true).value
userViewModel.observeLifecycleEvents(LocalLifecycleOwner.current.lifecycle)
SharpWalletTheme(darkTheme = isDarkTheme) {
val startDestination by splashViewModel.startDestination
val navController = rememberNavController()
val isUserAuth by userViewModel.isUserAuth
Surface(
modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
) {
RootNavigationGraph(
navHostController = navController,
startDestination = startDestination,
userViewModel = userViewModel,
toAuthUser = isUserAuth,
)
}
}
}
}
}
-更新1 我的splashViewModel如下-
class SplashViewModel @Inject constructor(
private val repository: UserRepository
) : ViewModel() {
private val _isLoading: MutableState<Boolean> = mutableStateOf(true)
val isLoading: State<Boolean> = _isLoading
private val _startDestination: MutableState<String> = mutableStateOf(Graph.ON_BOARDING)
val startDestination: State<String> = _startDestination
private val _isDarkMode: MutableState<Boolean> = mutableStateOf(true)
val isDarkMode: State<Boolean> = _isDarkMode
init {
viewModelScope.launch {
repository.readDarkModePreference().collect {
_isDarkMode.value = it
}
}
viewModelScope.launch {
repository.readOnBoardingState().collect { completed ->
if (completed) {
_startDestination.value = Graph.MAIN
} else {
_startDestination.value = Graph.ON_BOARDING
}
delay(500)
_isLoading.value = false
}
}
}
}
我认为您无法在显示后更改启动屏幕,您可以做的是快速从默认启动屏幕转换到与正确主题匹配的辅助“启动屏幕”。
@RequiresApi(Build.VERSION_CODES.S)
override fun onCreate(savedInstanceState: Bundle?) {
val splashScreen = installSplashScreen()
splashScreen.setOnExitAnimationListener { splashScreenProvider ->
val fadeOut = ObjectAnimator.ofFloat(splashScreenProvider.view, View.ALPHA, 0f)
fadeOut.duration = 500L // Or your desired duration
fadeOut.doOnEnd { splashScreenProvider.remove() }
fadeOut.start()
}
super.onCreate(savedInstanceState)
splashViewModel.isDarkMode.observe(this, { isDarkMode ->
if (isDarkMode) {
// Here, instead of changing the splash screen (which you can't after it's shown),
// You might transition to another screen or adjust the current theme, to mimic the splash screen
// adapting to the dark mode.
}
})
// Rest of your code...
}