2

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

2 Answers 2

1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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 🍻

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.