如何检查片段是否存在

如何检查片段是否存在

本文介绍了如何检查片段是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图谈谈活动中的片段.

I am trying to talk to the fragments from activity.

在我的MainActivity中,我可以添加多个片段,这样就可以了.

Here in my MainActivity I am adding multiple fragments ok so for fine.

我的主要要求是,如果片段已经添加,我不想添加.

My main requirement is I don't want to add if fragment is already added.

那么我们如何检查这种情况?

So how can we check this condition?

请帮我一个.

 private void intializingFragments(Fragment fragment) {

        FragmentManager fragmentManager = getSupportFragmentManager();

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fragment_container, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    private View.OnClickListener intialization() {

        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int getId = v.getId();

                if (getId == R.id.first) {
                    intializingFragments(new Fragment1());

                } else if (getId == R.id.second) {
                    intializingFragments(new Fragment2());

                } else if (getId == R.id.third) {
                    intializingFragments(new Fragment3());
                }
            }
        };
    }

推荐答案

您可以使用findFragmentByTag()或findFragmentById()函数来获取片段.如果提到的方法返回null,则该片段不存在.

You can use findFragmentByTag() or findFragmentById() functions to get a fragment. If mentioned methods are returning null then that fragment does not exist.

Fragment fragmentA = fragmentManager.findFragmentByTag("frag1");
if (fragmentA == null) {
  // not exist
} else {
  // fragment exist
}

例如:- http://wiki.workassis.com/android-load-two-fragments-in-one-framelayout/

这篇关于如何检查片段是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 08:14