I have one layout in two orientations - 1 landscape and 1 portrait.
/layout-land/main.xml
has two fragments:
<fragment android:id="@+id/fragment1" .. />
<fragment android:id="@+id/fragment2" .. />
/layout/main.xml
has only one fragment:
<fragment android:id="@+id/fragment1" .. />
Here's the MainActivity.java
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
firstFragment = (FirstFragment) getFragmentManager().findFragmentById(R.id.fragment1);
secondFragment = (SecondFragment) getFragmentManager().findFragmentById(R.id.fragment2);
}
Next, I start the MainActivity.java
in landscape mode. In this case,
- Both
firstFragment
andsecondFragment
refers to the fragments in the layoutlayout-land/main.xml
Then I rotate the screen to portrait mode, and the layout file layout/main.xml
should be loaded. In this case,
firstFragment
refers to theR.id.fragment1
secondFragment
referes to a non-existant fragment. Accessing any elements inside this throws a NullPointerException. (To be more precise,secondFragment
is notnull
here)
How this secondFragment
is initialized when there's no fragment defined inside the layout?
Edit: Reason found on Android Developer Documentation at http://developer.android.com/training/basics/fragments/creating.html:
When a configuration change causes the activity hosting these fragments to restart, its new instance may use a different layout that doesn't include the same fragments as the previous layout. In this case all of the previous fragments will still be instantiated and running in the new instance. However, any that are no longer associated with a tag in the view hierarchy will not have their content view created and will return false from isInLayout(). (The code here also shows how you can determine if a fragment placed in a container is no longer running in a layout with that container and avoid creating its view hierarchy in that case.)