0

I am trying to add and Remove a fragment in a relative layout. If in the relative layout (fragment container) is empty then add the fragment if not replace the fragment .

How to check whether the layout is empty or not , so that i do not get the error saying fragment already added.

MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
Bora
  • 1,933
  • 3
  • 28
  • 54

2 Answers2

2

try this code

YourFragment dFrag = (YourFragment) getSupportFragmentManager()
            .findFragmentById(R.id.detailfragment);

if (dFrag != null && dFrag.isInLayout()) {
    // do something
} else {
    // do something
}
Edward Falk
  • 9,991
  • 11
  • 77
  • 112
user2260168
  • 126
  • 1
  • 7
1

Not sure if this would be an answer, but i'd recommend you to use FragmentTransaction like this:

FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();

if(yourOldFragment.isAdded()) {
    ft.replace(R.id.your_container, yourNewFragment);
    ft.commit();
}

You can also have a look this link : Fragment duplication on Fragment Transaction

Community
  • 1
  • 1
Nari Kim Shin
  • 2,459
  • 1
  • 25
  • 33