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,305
  • 16
  • 71
  • 119
Bora
  • 1,913
  • 3
  • 27
  • 53

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,685
  • 9
  • 73
  • 108
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,349
  • 1
  • 23
  • 32