I have a Fragment SearchPageFragment
(representing the main view on a tablet) which itself contains two fragments inside of it:
<fragment android:name="com.test.fragments.SearchFormFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:id="@+id/searchFormFragment"
android:tag="searchFormFragmentTag">
<!-- Preview: layout=@layout/fragment_search_form -->
</fragment>
<fragment android:name="com.test.fragments.SearchResultsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/searchResultsFragment">
<!-- Preview: layout=@layout/fragment_search_results -->
</fragment>
Everything works fine - The page loads and everything works fine... Until you change the orientation. When you do the following error occurs:
java.lang.IllegalArgumentException: Binary XML file line #10: Duplicate id 0x7f08001f, tag searchFormFragmentTag, or parent id 0x0 with another fragment for com.test.fragments.SearchFormFragment
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:262)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)
Here is the sequence of calls when you switch the orientation:
SearchPageFragment(4911): Creating...
SearchPageFragment(4911): Inflating...
SearchFormFragment(4911): Creating...
SearchFormFragment(4911): Inflating...
SearchResultsFragment(4911): Creating...
SearchResultsFragment(4911): Inflating...
// Change Orientation
SearchPageFragment(4911): Pausing...
SearchFormFragment(4911): Pausing...
SearchResultsFragment(4911): Pausing...
SearchPageFragment(4911): Destroying...
SearchFormFragment(4911): Destroying...
SearchResultsFragment(4911): Destroying...
// All Seems Normal - But...
SearchPageFragment(4911): Creating...
SearchPageFragment(4911): Creating...
SearchPageFragment(4911): Inflating...
SearchFormFragment(4911): Creating...
SearchFormFragment(4911): Inflating...
SearchResultsFragment(4911): Creating...
SearchResultsFragment(4911): Inflating...
SearchPageFragment(4911): Inflating...
// SearchPageFragment has started twice and crashes when the second one inflates a ***unique*** component
AndroidRuntime(4911): Shutting down VM
Does anybody know why my container Fragment would be called twice on orientation change?
Got it:
The bug was with the holder activity for SearchPageFragment adding the
Fragment
twice.Android will always retain fragments attached to a View when an orientation change occurs.
Because of this, you need to ensure that if you're adding a Fragment in your
onCreate()
method you surround it's creation (and addition/replacement transation) with an if statement to check thatsavedInstanceState
is null (If it's not null it indicates an orientation change has occurred).I solved the problem using this .