faizal
faizal

Reputation: 3565

How to avoid duplicate fragments?

I have a button in my fragment (fragment_x) with the below OnClickListener:

    private void onClickAddButton(View view){
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment_y fragment_y = new Fragment_y();
        fragmentTransaction.add(R.id.rl_activity_main_container, fragment_x);
        fragmentTransaction.commit();
    }

The problem is that this button is always visible, so clicking it again will add one more fragment_y and the screen gets messed up. How how do I check whether fragment_y has already been added, so that I can avoid creating a duplicate fragment_y?

Upvotes: 1

Views: 4495

Answers (1)

Simon Marquis
Simon Marquis

Reputation: 7516

You can ask the FragmentManager if the Fragment is already added:

    FragmentManager fm = getFragmentManager();
    Fragment fragment = fm.findFragmentByTag(tag);
    if (fragment == null) {
        // fragment must be added
        fragment = new Fragment();
        fm.beginTransaction().add(R.id.container, fragment, tag);
    } else {
        // fragment already added
    });

Upvotes: 7

Related Questions