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

前端 未结 7 2115
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  -上瘾入骨i
    2020-11-28 06:32

    Here is a recursive solution in Kotlin. Given the top-most fragments of an activity, returns all the descendant fragments.

    fun recursiveGetFragments(parents: List): List {
        val result = parents.toMutableList()
        for(root in parents) {
            if (root.isVisible) {
                result.addAll(recursiveGetFragments(root.childFragmentManager.fragments))
            }
        }
        return result
     }
    

    It is used as:

    val fragmentList = recursiveGetFragments(supportFragmentManager.fragments)
    

提交回复
热议问题