faizal faizal - 7 months ago 83
Android Question

How to avoid duplicate fragments?

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


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);

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?


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