android / architecture-samples

A collection of samples to discuss and showcase different architectural tools and patterns for Android apps.
Apache License 2.0
44.5k stars 11.66k forks source link

launchFragmentInHiltContainer does not work when using Jetpack Navigation #780

Open aljohnston112 opened 3 years ago

aljohnston112 commented 3 years ago

I had to change the method to use findNavController

aljohnston112 commented 3 years ago

I think the problem is android:launchMode="singleTop"

Here is my hack: inline fun <reified T : Fragment> launchFragmentInHiltContainer( navHost : Int, destFragment : Int, fragmentArgs: Bundle? = null, @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme) { val startActivityIntent = Intent.makeMainActivity( ComponentName(ApplicationProvider.getApplicationContext(), ActivityMain::class.java)). putExtra(FragmentScenario.EmptyFragmentActivity.THEME_EXTRAS_BUNDLE_KEY, themeResId) ActivityScenario.launch<ActivityMain>(startActivityIntent).onActivity { activity -> activity.findNavController(navHost).navigate(destFragment, fragmentArgs) } } Not sure how good it is...

aljohnston112 commented 3 years ago

Here I set the graph and then perform navigation after the fact. inline fun <reified T : Fragment> launchFragmentInHiltContainer( navController: NavController, navHost: Int, navGraph: Int, ): ActivityScenario<ActivityMain> { val startActivityIntent = Intent.makeMainActivity( ComponentName( ApplicationProvider.getApplicationContext(), ActivityMain::class.java)) return ActivityScenario.launch<ActivityMain>(startActivityIntent).onActivity { activity -> val navHostFragment = activity.supportFragmentManager.findFragmentById(navHost) as NavHostFragment Navigation.setViewNavController(navHostFragment.requireView(), navController) navController.setGraph(navGraph) } }