【问题标题】:What Fragments am I hosting and displaying?我托管和展示了哪些片段?
【发布时间】:2015-03-27 23:57:49
【问题描述】:

有没有办法知道哪个Fragment 当前显示Activity 的给定<fragment> 容器中,而无需通过onAttachFragment 回调跟踪所有更改?

当用户按下返回键时,当片段事务发生时,是否甚至可以知道显示哪些片段?在后一种情况下,即当 Fragment 因返回而重新显示时,onAttach 不会被调用。

【问题讨论】:

    标签: android


    【解决方案1】:

    根据我的经验,确定正在显示哪个片段的唯一方法是自己仔细跟踪。
    例如,您可以在 Activity 中创建一个变量:

    Fragment mCurrentDisplayedFragment;
    

    然后每当用户请求不同的片段时:

    mCurrentFragment = (Fragment) userRequestedFragment;
    fragmentManager.replace(container, mCurrentFragment, tag);
    

    然后,当您需要对当前显示的片段执行操作时,您可以通过 try/catch 强制转换或使用 instanceof 对其进行分类。

    您还可以通过在活动中覆盖该方法来处理后按行为:

    @Override
    public void onBackPressed() {
        int stackSize = fragmentManager.getBackStackEntryCount(); 
        // This counts up from the bottom so the most recent fragment is the biggest number/size
        backFragId = fragmentManager.getBackStackEntryAt(stackSize);
        // Get a handle on the fragment that is about to be popped
        mCurrentFragment = fragmentManager.findFragmentById(backFragId);
        super.onBackPressed();
    }
    

    另外,您确定当片段从堆栈中弹出时不会调用 onAttach 吗?我似乎记得它会,你可以通过那里创建的接口调用(如果你有一个并且活动实现了它)将片段注册为当时活动中的当前片段。

    但是要直接回答您的问题,没有一种内置方法可以只知道当前显示的片段(并且可能不止一个!)。其实施细节由您决定。希望我已经给了你一些关于如何处理它的想法。您可能还会发现 the FragmentManager documentation 很有帮助。

    【讨论】:

    • 感谢您的回答。 onAttach 方法没有被调用,不幸的是,我认为是因为从后面的堆栈中弹出的 Fragment 已经附加了。我无法相信他们构建的 Fragment 框架有多么混乱。
    • @Antonio Sesto 有人向我指出 Fragment 的 onResume 方法在每次显示时都会被可靠地调用。这将是调用 Activity 接口以注册 Fragment 的理想位置。
    【解决方案2】:

    每次在容器中添加/替换片段时,都使用标签:

    FragmentTransaction ft = getFragmentManager().beginTransaction();       
    ft.add(R.id.container, fragment, tag).commit();
    

    然后你可以发现片段当前是否可见:

    Fragment fg = getFragmentManger().findFragmentByTag(tag);
    if(fg.isVisible())
        //fg is the current visible fragment
    

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多