有没有办法获取活动中所有当前活动片段的引用? [英] Is there a way to get references for all currently active fragments in an Activity?

查看:30
本文介绍了有没有办法获取活动中所有当前活动片段的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有找到一种简单的方法来获取活动中所有当前处于活动状态(可见,当前处于恢复状态)的片段.在我的活动中没有自定义簿记可能吗?FragmentManager 似乎不支持此功能.

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 Activity? It seems that the FragmentManager doesn't support this feature.

推荐答案

看起来 API 当前缺少像getFragments"这样的方法.
然而,使用类 Activity 的事件onAttachFragment"应该很容易做你想做的事.我会做类似的事情:

Looks like the API currently misses a method like "getFragments".
However using the event "onAttachFragment" of class Activity it should be quite easy to do what you want. I would do something like:

List<WeakReference<Fragment>> fragList = new ArrayList<WeakReference<Fragment>>();
@Override
public void onAttachFragment (Fragment fragment) {
    fragList.add(new WeakReference(fragment));
}

public List<Fragment> getActiveFragments() {
    ArrayList<Fragment> ret = new ArrayList<Fragment>();
    for(WeakReference<Fragment> ref : fragList) {
        Fragment f = ref.get();
        if(f != null) {
            if(f.isVisible()) {
                ret.add(f);
            }
        }
    }
    return ret;
}

如果没有就绪方法从对象中读取状态(示例中的 isActive()),我将覆盖 onResume 和 onPause 以设置一个标志(可能只是一个 bool 字段).
这已经是一些自己的簿记,但考虑到您想要实现的非常具体的目标(状态相关列表),我认为仍然非常有限.

In case there's no ready method to read the state from the object (isActive() in the example), I would override onResume and onPause to set a flag (could be just a bool field).
That's already some own bookkeeping, but still very limited in my opinion considering the quite specific goal you want to achieve (status dependent list).

这篇关于有没有办法获取活动中所有当前活动片段的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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