android 导航图配置更改

android navigation graph configration change

我正在尝试使用 android 导航组件遵循单个 activity 模式,我的 %99 片段是纵向的,但我需要制作一个新的片段可以是纵向的或横向的而不添加新的 activity我怎样才能实现。我找不到任何资源。可能吗 ?如果是怎么回事?

以下步骤可能对您有用:

  1. 不要从 AndroidManifest.xml 锁定屏幕方向。

  2. NavHostFragmentchildFragmentManager 上的 Activity 内注册一个侦听器,它将在片段生命周期更改时执行回调

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. 按照此 guide 到 lock/unlock 屏幕方向,具体取决于哪个 Fragment 是可见的,从上面的回调中。

注意

根据应用的导航设计,片段标记或实例类型可用于在生命周期回调中编写条件语句。

别忘了从 Activity.onDestroy()

unregisterFragmentLifecycleCallbacks

干杯

您可以添加NavController.OnDestinationChangedListener并根据当前片段设置方向。

将此添加到您的 activity 的 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
    }
}