简体   繁体   English

片段的OnDestroyView永不称为按“后退”按钮

[英]OnDestroyView of a fragment is never called pressing Back button

In a basic application based on fragments navigation, fragment B replaces fragment A. Then I press the back button to return to fragment A and I would hope that OnDestroyView of fragment B would be called but it is never called. 在基于片段导航的基本应用程序中,片段B替换了片段A。然后按“后退”按钮返回片段A,我希望可以调用片段B的OnDestroyView,但从不调用它。 I use AddToBackStack() in the transaction. 我在事务中使用AddToBackStack()。 Is it normal? 正常吗

I use AppCompat 26.0 and Xamarin Android. 我使用AppCompat 26.0和Xamarin Android。

UPDATE : 更新

It can be easily replicated with any Xamarin example. 可以使用任何Xamarin示例轻松复制它。 For example https://developer.xamarin.com/samples/monodroid/FragmentsWalkthrough/ 例如https://developer.xamarin.com/samples/monodroid/FragmentsWalkthrough/

In DetailsFragment.cs, add the following: 在DetailsFragment.cs中,添加以下内容:

    public override void OnDestroyView()
    {
        base.OnDestroyView();
    }

Then if you add a breakpoint at OnDestroyView, you will see that it is never called even when you press the Back button. 然后,如果在OnDestroyView上添加一个断点,即使按“后退”按钮,也将永远不会调用该断点。 In other words, each time I add a fragment, a new instance is created, but never destroyed. 换句话说,每次添加片段时,都会创建一个新实例,但不会销毁它。

As seen in Fragment Lifecycle a fragment which is part of the backstack is usually kept in stopped state and not destroyed . 片段生命周期中可以看到,作为堆栈的一部分的片段通常处于stopped状态,并且不会destroyed onDestroyView() is part of the destroy phase and will not be called if the fragment is merely stopped . onDestroyView()是销毁阶段的一部分,如果仅stopped了片段,则不会调用它。

So yes, that is normal. 是的,这很正常。 Try to use onStop() instead. 尝试改用onStop()

After 2 days, finally I have found the problem. 2天后,终于找到了问题所在。 It seems a Xamarin bug. 似乎是Xamarin错误。 I have changed the Target from Android 8.0 to Android 7.1. 我已将Target从Android 8.0更改为Android 7.1。 I compiled it and it worked fine. 我编译了它,效果很好。 Then I changed back to 8.0 again and it started to work fine too. 然后我再次改回8.0,它也开始正常工作。

I could replicate this solution with the Xamarin examples too. 我也可以使用Xamarin示例来复制此解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM