【问题标题】:FragmentManager know when a fragment resumedFragmentManager 知道片段何时恢复
【发布时间】:2015-08-05 21:27:06
【问题描述】:

我有一个FragmentManager,用于将Fragments 添加到backStack

FragmentTransaction ft = getFragmentManager().beginTransaction();
PUCCoursesSubjectList detail = new PUCCoursesSubjectList();
detail.item = item;

ft.add(R.id.container_frame, detail, "courses_detail");
ft.addToBackStack(null);
ft.commit();

一旦堆栈上有几个Fragments,我会弹出一个,但我需要知道上一个片段何时再次显示。

onResume 似乎不适用于这里。我应该使用另一种方法来了解 Fragment(已经在 FragmentManger 中)何时出现?

【问题讨论】:

    标签: java android android-fragments android-listfragment


    【解决方案1】:

    接受的答案无效:getFragmentManager 在某些情况下可能返回 null(即 Activity 已被销毁)

    现在最好使用 Lifecycle,如下例所示:

      if( getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED) )
      {
          // Do whatever you need
      }
    

    【讨论】:

    • 我可以知道我必须从哪里使用此代码吗?我是指片段还是活动?
    • 两者都使用androidx版本。
    【解决方案2】:

    当你弹出你的片段时,你可以通过你提供的标签从片段管理器中获取你的另一个片段,并在你的片段中调用一个公共方法。

    YourFragment fragment = (YourFragment) getFragmentManager().findFragmentByTag("FRAGMENT_TAG");
    
    if (fragment != null) {
       fragment.callMethod();
    }
    

    【讨论】:

    • 我会从哪里调用这个?从我弹出的片段中的方法?来自onDestroy()?
    • 取决于你在哪里需要它。您可以在可以访问上下文的任何地方调用它(托管您的片段的活动)。在您的情况下,您提到您弹出一个片段,您可以在那里调用它吗?
    • 是的,刚刚在popped Fragment的onDestroy()方法中测试过,效果很好!谢谢!
    【解决方案3】:

    您可以通过标签检查标签是否可见且不为空

    MyFragment myFragment = (MyFragment)getFragmentManager().findFragmentByTag("MY_FRAGMENT");
    if (myFragment != null && myFragment.isVisible()) {
       // add your code here
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-02
      • 1970-01-01
      • 2016-04-04
      • 2014-06-23
      • 2013-01-06
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多