3

So I've found a few similar cases, but nothing about this specific case.

  1. I have a FrameLayout which I gave the id "container", and contains a few different fragments.

  2. In my code for the activity that contains that FrameLayout, I'm trying to switch between the fragments with a function that receives a fragment.

  3. In that code:

    a. I have defined private FragmentManager fm = getSupportFragmentManager();

    b. I have defined FragmentTransaction ft; to use later.

    c. My function is:

    private void setActiveFragment(Fragment fragment){
    
    //Determine which button should be marked as "active"
    determineButtonByFragment(fragment);
    
    //Repalce fragment
    ft = fm.beginTransaction();
    ft.replace(R.id.container, fragment);
    ft.addToBackStack(String.valueOf(fragment.getId()));
    ft.commit();
    }
    

Any idea why i would get this error on the "replace"?

EDIT: Ok, I just realized a bit more about fragments. Since all 5 fragments are added to the FrameLayout, the "replace" won't work. You get the "can't chance container ID error" when you're trying to move a fragment from 1 parent view to another (Or in this, case, to the same one), without detaching it first. Let's say I have fragments A, B, C, D, E. If I want to replace to fragment B right now, I won't be able to do it until I remove it from it's original parent (Or at least that's how I think it works. please enlighten me otherwise). The only question that remains now, is how do I switch between my fragments correctly...

Cookienator
  • 637
  • 1
  • 7
  • 25

1 Answers1

2

Alright, apparently you cannot use the "replace" method on fragments which are hard-coded in the layout: Replacing a fragment with another fragment inside activity group

What I have to do now, is inside the function, to find a way to determine the fragment I want to display, create a new instance of it, and use "replace" on it.

Community
  • 1
  • 1
Cookienator
  • 637
  • 1
  • 7
  • 25