Android 中选项卡的生命周期

Lifecycle of tabs in Android

我正在使用 TabLayout 和 ViewPager 实现 5 个选项卡作为 master/detail 布局的详细视图。

当我在主视图中单击某个项目时,它会创建我的详细视图,而详细视图又会创建必要的选项卡。创建详细视图时,将调用选项卡的 onResume() 方法。 当我回到主视图时,详细视图的 onPause() 被调用,但选项卡的 onPause() 没有被调用

这是一个问题,因为我在每个选项卡的 onResume() 方法中订阅了事件,但是应该在每个选项卡的 onPause() 中完成的取消订阅从未发生。

因此,如果我在主视图中的项目上单击 n 次,则订阅完成 n 次,每个事件处理 n 次。

我试过这个解决方案https://looksok.wordpress.com/2013/11/02/viewpager-with-detailed-fragment-lifecycle-onresumefragment-including-source-code/ 我在 SO 答案中找到的,但它不起作用,因为 onFragmentPause() 中片段的 ID(Id 0)与 onFragmentResume() 中片段的 ID 不同(因此订阅在 onFragmentPause() 中为 null ).

我不明白如何让选项卡片段在每次单击项目时都不会重复,或者如何让它们调用它们的 onPause() 方法。

AndroidDev 中所述,在处理嵌套片段时应调用 getChildFragmentManager() 而不是 getSupportFragmentManager()。

我对我的视图寻呼机适配器使用了错误的方法。 我将其更改为:

adapter = new PagerAdapter(getChildFragmentManager(), tabLayout.getTabCount());