Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

android - How to check if the fragment exists

I am trying to talk to the fragments from activity.

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?

Please help me some one.

code:-

 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());
                } 
            }
        };
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

for example:- http://wiki.workassis.com/android-load-two-fragments-in-one-framelayout/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...