Android NavController:onResume / onPause回调重新排序

问题描述 投票:0回答:1

我正在为Android导航库的非常奇怪的行为而苦苦挣扎。

我使用这些回调创建了一个片段(为了显示全屏内容,实际的系统UI切换在activity.setFullscreen中实现:]

class FullscreenFragment : Fragment() {
    ...
    override fun onResume() {
        super.onResume()
        activity.setFullscreen(true)
    }

    override fun onPause() {
        super.onPause()
        activity.setFullscreen(false)
    }
    ...

}

假设我们有2个不同的片段,FragmentAFragmentB都继承了此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以外)并使用自然的生命周期回调顺序?

提前感谢!

android fragmenttransaction android-jetpack-navigation
1个回答
0
投票

您可以在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);
        }
    }
    ...

}
© www.soinside.com 2019 - 2024. All rights reserved.