android navigation graph configration change

651 Views Asked by At

I am trying to follow single activity pattern with android navigation component and my %99 of fragment are portrait but I need to make a new fragment can be portrait or landscape without adding new activity how can I achieve. I could't find any resource. is it possible ? if it is how ?

2

There are 2 best solutions below

0
On BEST ANSWER

You can add NavController.OnDestinationChangedListener and set orientation according to the current fragment.

Add this in your activity's onCreate:

val navHostFragment = supportFragmentManager.findFragmentById(R.id.your_nav_host_fragment) as NavHostFragment
navHostFragment.navController..addOnDestinationChangedListener { _, destination, _ ->
    if (destination.id == R.id.destination_with_orientation) {
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
    } else {
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
    }
}
0
On

The following steps could be useful for you:

  1. Don't lock screen orientation from AndroidManifest.xml.

  2. Register a listener inside Activity on the childFragmentManager of the NavHostFragment, that will execute callbacks on fragment lifecycle change

override fun onCreate(savedInstanceState: Bundle?) {
   //...
   
   val fragments = supportFragmentManager.fragments
   check(fragments.size == 1) {
       val baseMessage = "Expected 1 fragment to host the app's navigation. Instead found ${fragments.size}."
       if (fragments.size == 0) {
           val suggestion = "(Make sure you specify `android:name=\"androidx.navigation.fragment." +
                   "NavHostFragment\"` or override setUpNavigationGraph)"
           "$baseMessage $suggestion"

       } else baseMessage
   }

   with(fragments[0].childFragmentManager) {
       registerFragmentLifecycleCallbacks(CustomFragmentLifecycleCallbacks(), false)
   }
}

private inner class CustomFragmentLifecycleCallbacks : FragmentManager.FragmentLifecycleCallbacks() {
   override fun onFragmentViewCreated(fm: FragmentManager, f: Fragment, v: View, savedInstanceState: Bundle?) {}
   override fun onFragmentViewDestroyed(fm: FragmentManager, f: Fragment) {}
}
  1. Follow this guide to lock/unlock screen orientation depending upon which Fragment is visible, from the above callback.

NOTE

Fragment tags or instance type could be used for writing conditional statements inside the lifecycle callbacks, based on app's navigation design.

Don't forget to unregisterFragmentLifecycleCallbacks from Activity.onDestroy()


Cheers