我正在为Android导航库的非常奇怪的行为而苦苦挣扎。
我使用这些回调创建了一个片段(为了显示全屏内容,实际的系统UI切换在activity.setFullscreen
中实现:]
class FullscreenFragment : Fragment() {
...
override fun onResume() {
super.onResume()
activity.setFullscreen(true)
}
override fun onPause() {
super.onPause()
activity.setFullscreen(false)
}
...
}
假设我们有2个不同的片段,FragmentA
和FragmentB
都继承了此FullscreenFragment
。
[当我使用FragmentA
方法从FragmentB
导航到NavController.navigate
时出现问题-在这种情况下,FragmentB.onResume
被称为FragmentA.onPause
之前。过渡完成后,这将导致全屏模式被禁用。当我从FragmentB
导航回到FragmentA
时,也会发生相同的情况-FragmentA.onResume
会先于FragmentB.onPause
。
我怀疑这是由于androidx.navigation.fragment.FragmentNavigator
的实现而发生的,该实现在提交片段事务之前在ft.setReorderingAllowed(true);
方法内调用了public NavDestination navigate
。
此调用在实际的私有实现中进行硬编码的原因是什么?是否有任何方法可以克服此问题(除了实现自定义FragmentNavigator以外)并使用自然的生命周期回调顺序?
提前感谢!
您可以在onResume
中增加一个计数器,然后在onPause
中减少一个计数器,然后在它等于零时才在setFullscreen(false)
中减少。
例如:
class FullscreenFragment : Fragment() {
...
private int fragmentCount = 0;
override fun onResume() {
super.onResume();
if (fragmentCount == 0) {
activity.setFullscreen(true);
}
fragmentCount++;
}
override fun onPause() {
super.onPause();
fragmentCount--;
if (fragmentCount == 0) {
activity.setFullscreen(false);
}
}
...
}