我正在尝试使用android导航组件遵循单一活动模式,我的99%的片段是纵向的,但我需要在不添加新活动的情况下制作一个新的片段,可以是纵向或横向的,我该如何实现。我找不到任何资源。有可能吗?如果是怎么回事?
您可以添加NavController.OnDestinationChangedListener
并根据当前片段设置方向。
将其添加到活动的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
}
}
以下步骤可能对您有用:
-
不要从
AndroidManifest.xml
锁定屏幕方向。 -
在
NavHostFragment
的childFragmentManager
上的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) {}
}
- 按照本指南从上述回调锁定/解锁屏幕方向,具体取决于哪个
Fragment
可见
注意
根据应用程序的导航设计,片段标记或实例类型可用于在生命周期回调中编写条件语句。
不要忘记从Activity.onDestroy()
注销FragmentLifecycleCallbacks
干杯