Can I detect whether Fragment is already created or called?

浪子不回头ぞ 提交于 2020-01-25 09:03:07

问题


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?


回答1:


The fragments have isVisible() method .

            if(fragment.isVisible()){
                //your code.//
            }

By this you can see if the fragment is already created or not.




回答2:


Test if onCreateView has been called

public abstract class SubFragment extends Fragment
{
    protected boolean onCreateViewCalled = false;

    public boolean hasOnCreateViewBeenCalled()
    {
        return onCreateViewCalled;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup Container, Bundle state){
        onCreateViewCalled = true;
        return null;
    }
}

for more details please read here




回答3:


You could use findFragmentByTag() :

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
    }


来源:https://stackoverflow.com/questions/58856484/can-i-detect-whether-fragment-is-already-created-or-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!