我有一个片段SearchPageFragment
(代表平板电脑上的主视图),它本身包含两个片段:
<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>
一切正常 - 页面加载,一切正常......直到你改变方向。当您执行以下错误时:
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)
切换方向时,这是一系列调用:
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
有人知道为什么我的容器片段会在方向更改时被调用两次吗?
答案 0 :(得分:5)
知道了:
错误在于SearchPageFragment的持有者活动两次添加Fragment
。
当发生方向更改时,Android将始终保留附加到视图的片段。
因此,您需要确保如果您在onCreate()
方法中添加片段,则使用if语句围绕它创建(以及添加/替换转换)以检查savedInstanceState
为null(如果它不为null,则表示已发生方向更改)。
if(savedInstanceState == null) {
// Add fragment code here
}
答案 1 :(得分:1)
我用这个解决了这个问题。
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (root != null) {
ViewGroup parent = (ViewGroup) root.getParent();
if (parent != null)
parent.removeView(root);
}
try {
root = inflater.inflate(R.layout.activity_explore,container,false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
return root;
}