Android 在片段中重新创建视图时强制关闭(重复片段)

Android 在片段中重新创建视图时强制关闭(重复片段),android,android-fragments,android-actionbar,Android,Android Fragments,Android Actionbar,我在这里学习教程 在ArtistFragment.class public class ArtistFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View fragView = inflater.inflate

我在这里学习教程

ArtistFragment.class

public class ArtistFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View fragView = inflater.inflate(R.layout.main_fragment, container, false);
        return fragView;
    }
}
首先,我选择Tab
Artist
它显示视图,但当我切换到另一个选项卡时,再次切换回
Artist
选项卡,它会导致强制关闭

main_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="10dp"
    android:id="@+id/frags" >

    <fragment 
        android:name="com.android.custom.FragmentLeft"
        android:id="@+id/fragment_left"
        android:layout_weight="0.25"
        android:layout_width="0dp"
        android:layout_height="match_parent"/>
    <fragment 
        android:name="com.android.custom.FragmentRight"
        android:id="@+id/fragment_right"
        android:layout_weight="0.75"
        android:layout_width="0dp"
        android:layout_height="match_parent"/>

</LinearLayout>

为什么
R.layout.main_fragment
中有两个片段?
片段
不能有另一个
片段
在其内部…它必须在
活动
内部。是否有一个
artist\u fragment.xml
是您想要充气的?

将代码包装在中的
onCreate
方法中

if(savesInstanceState == null) {
    // your code here
}
这将阻止框架尝试根据方向或活动更改(我认为这就是正在发生的事情)重新创建所有内容。在大多数情况下,您应该在每一个活动中都使用这个框架,这样框架就可以像大多数人期望的那样运行

if(savesInstanceState == null) {
    // your code here
}