有没有一种方法可以用于在活动所有当前活动的片段引用? [英] Is there a way to get references for all currently active fragments in an Activity?

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

问题描述

我还没有找到一种简单的方式来获得所有当前活动的(可见,目前已恢复状态)片段在一个活动。是否有可能没有在我的活动定制记账?看来,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。
但是使用事件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设置标志(可能只是一个布尔场)。
这是已经有一些自己记账,但仍然很有限,我认为考虑到你想要达到的相当具体的目标(状态相关的列表)。

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天全站免登陆