Search code examples
androidxmlviewmodelsplash-screen

Splash Screen Android XML


I'm trying implement splash screen using Splash Screen Api for android app with navigation component. I've faced with problem when i need to keep splash for some state from fragment viewmodel and in the same time app crashes if i call installSplashScreen not in MainActivity. I don't know how resolve this, seems i need add custom fragment splash without api. Any ideas?

installSplashScreen().apply {
     setKeepOnScreenCondition {
         homeViewModel.homeCollectionState.value !is HomeCollectionState.Loading &&
            homeViewModel.homeCollectionState.value !is HomeCollectionState.Idle
         }
}

Solution

  • You could attach the ViewModel to the activity and the fragment.

    You need to scope it to the activity to make sure you get the same instance.

    In your activity:

    val viewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
    

    In your fragment:

    val viewModel = ViewModelProvider(requireActivity()).get(HomeViewModel::class.java)