如何知道是否所有的片段分离? [英] How to know if all fragments were detached?

查看:225
本文介绍了如何知道是否所有的片段分离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我使用的主要活动,其中有一个抽屉式导航,并作为用户去从抽屉中的选项,它会改变片段beging相应的显示选择的选项。

On my app I am using a Main Activity, which has a Navigation Drawer, and as the user go to an options from the drawer, it will change the fragment beging displayed accordingly to the option selected.

如果用户打的返回键几次,它就会回到一个点,它会达到我的主要活动,这是一个空白,空布局。

If the user hit's "Back button" several times, it will go back to a point in which it will reach my Main Activity, which is a blank and empty layout.

当我到了这个地步(我的主要activit,空的),我想退出应用程序,或者,打开抽屉式导航栏。

When I reach this point (my main activit, empty), I would like to exit the app, or, open the Navigation Drawer.

问题是,我不知道,让我发现,我回到了主要活动的任何事件。我查了onResume,但它从来不叫,这是有道理的,因为主要的活动从来没有停止过。

The problem is, I don't know any event that shows me that I am back to the Main Activity. I checked the onResume, but it's never called, which makes sense, since the main activity has never been stopped.

我想也许会有从片段经理认为将在当一个片段分离的主要活动被称为一个事件,并从那里我可以检查是否有没有在所有连接的片段?

I thought perhaps there would be an event from the fragment manager that would be called on the Main Activity when a fragment was detached, and from there I could check if there was no fragment at all attached?

推荐答案

当你把你的第一个片段,一个标签添加到它。类似

When you push your first fragment, add a tag to it. Something like

transaction.replace( R.id.rootContainer, firstFragment, "rootFragment");

每当用户presses后退按钮,你可以从FragmentManager让您rootFragment

Whenever user presses back button, you can get your rootFragment from FragmentManager

FirstFragment myFragment = (FirstFragment) getSupportFragmentManager().findFragmentByTag("rootFragment");

和检查,如果该片段可见或不可见,由 myFragment.isVisible(),如果没有,然后继续出栈,如果是可见的,这意味着用户是在第一片段。现在,您可以退出应用程序,或显示您的菜单的抽屉里。

And check if this fragment is visible or not, by myFragment.isVisible(), if not, then keep popping the stack, if it is visible, it means user is on the first fragment. Now you can either quit the app, or show your menu drawer.

这篇关于如何知道是否所有的片段分离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆