我可以检测是否已经创建或调用了Fragment吗? [英] Can I detect whether Fragment is already created or called?

查看:109
本文介绍了我可以检测是否已经创建或调用了Fragment吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以检测要调用的片段是否已被调用或已创建,以便我可以重用它而不是重新创建它吗?

Can I detect whether the Fragment I am going to call is already called or created so that I can reuse it instead of recreating it?

推荐答案

您可以使用 findFragmentByTag():

查找由给定标签标识的片段由XML夸大或添加到事务中时提供的.这个首先搜索当前添加到经理的活动;如果找不到这样的片段,那么所有片段搜索当前位于后方堆栈中的内容.

Finds a fragment that was identified by the given tag either when inflated from XML or as supplied when added in a transaction. This first searches through fragments that are currently added to the manager's activity; if no such fragment is found, then all fragments currently on the back stack are searched.

因此您的代码应如下所示:

So your code should look like this:

    val tag = "MyFragment"
    // add a tag to transaction
    supportFragmentManager.beginTransaction()
        .replace(R.id.frame, fragment, tag)
        .commit()


    // check if fragment exists by the given tag
    var instance = supportFragmentManager.findFragmentByTag(tag)
    if (fragment == null) {
        instance = MyFragment.newInstance()
    } else {
        // reuse fragment instance
    }

这篇关于我可以检测是否已经创建或调用了Fragment吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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