I'm creating FrameLayouts and Fragments at runtime. I have a LinearLayout (R.id.presentationRight) in my xml file. Every time I need a new fragment within that layout, I do the following.
- Create a new FrameLayout and add it to the LinearLayout
- Generate an ID for the FrameLayout so FragmentTransaction can reference it
- Create a new Fragment
- Perform a FragmentTransaction to place the new Fragment in the new frame.
The code looks like this
LinearLayout presentationRight = (LinearLayout) findViewById(R.id.presentationRight);
FrameLayout bluRayFrame = new FrameLayout(MainActivity.this);
bluRayFrame.setId(View.generateViewId());
presentationRight.addView(bluRayFrame);
BluRayFragment bluRayFragment = new BluRayFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(bluRayFrame.getId(), bluRayFragment);
fragmentTransaction.commit();
It works perfectly. I can run as many copies of this method as I want and it always adds another instance of this fragment to the LinearLayout, which is exactly what I want.
The problem comes when the screen rotates. When I had a single existing frame in the layout and I was just replacing the existing frame, rotation worked perfectly. You could view the app in portrait or landscape and it always reloaded the fragment perfectly. However, now that the framelayout I'm addressing isn't actually in the XML file, it crashes the app and gives me a null pointer within the Fragment itself when it tries to reference container.getContext(). I'm assuming that since the Fragment isn't actually tied to the xml file that when the Activity reloads on rotate, the container isn't there so the context isn't there, but I don't know how to fix it.
I'm not doing anything special to handle the rotation right now, just letting the activity do everything on it's own.
Thoughts? I'd really like to avoid creating a bunch of framelayouts in code and referencing them individually because i don't know how many of these fragments will eventually be necessary, so writing it open ended seems like the best way to handle things if I can figure out how.