判断当前Activity是否有DialogFragment显示

DialogFragment一种情况是在当前Activity上启动,一种情况是在Fragment上启动,判断当前fragmentManager上是否有,以及遍历判断子fragment上是否有,即可确定是否有DialogFragment展示。

使用方式:

// supportFragmentManager为当前Activity的fragmentManager
hasDialogFragment(supportFragmentManager)
    private fun hasDialogFragment(fragmentManager: FragmentManager): Boolean {
        if (fragmentManager.fragments.find {
                it is DialogFragment
            } != null) {
            // 存在弹框
            return true
        }

        if (fragmentManager.fragments.find {
                // 子片段管理器中含有弹框
                fragmentHasDialogFragment(it)
            } != null) {
            // 子Fragment上含有弹框
            return true
        }

        return false
    }

    /**
     * 遍历查询fragment上是否有dialogFragment
     */
    private fun fragmentHasDialogFragment(fragment: Fragment): Boolean {
        val childFragments = fragment.childFragmentManager.fragments
        if (childFragments.isEmpty()) {
            return false
        }
        childFragments.forEach {
            if (it is DialogFragment) {
                return true
            }
            if (fragmentHasDialogFragment(it)) {
                return true
            }
        }
        return false
    }

你可能感兴趣的:(Android知识归纳,android)