Is there a way to get references for all currently active fragments in an Activity?

前端 未结 7 2123
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 05:46

I haven\'t found a simple way to get all currently active (visible, currently in Resumed state) Fragments in an Activity. Is it possible without custom bookkeeping in my Act

7条回答
  •  隐瞒了意图╮
    2020-11-28 06:41

    If you use Android Support Library, then you can call hidden FragmentManager.getFragments() method:

    public List getVisibleFragments() {
        List allFragments = getSupportFragmentManager().getFragments();
        if (allFragments == null || allFragments.isEmpty()) {
            return Collections.emptyList();
        }
    
        List visibleFragments = new ArrayList();
        for (Fragment fragment : allFragments) {
            if (fragment.isVisible()) {
                visibleFragments.add(fragment);
            }
        }
        return visibleFragments;
    }
    

提交回复
热议问题