为什么我的onCreateView方法被调用两次?

NSo*_*uth 4 android oncreate android-activity

在调试另一个问题时,我意识到我onCreateView的一个活动的方法被调用了两次.我是编程的新手,我不完全理解android活动加载时如何调用这些方法,但对我来说它似乎不会被调用两次.消除了我的大部分代码,我仍然会看到我的System.out消息两次.

public class AddCourse extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_course);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new AddCourseFragment()).commit();
        }
    }

    public static class AddCourseFragment extends Fragment {

        View rootView;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
            rootView = inflater.inflate(R.layout.fragment_add_course,
                container, false);
                        System.out.println("I see this TWICE!!!!");
            return rootView;
        }       
    }
}
Run Code Online (Sandbox Code Playgroud)

这几乎与我的主要活动实现完全一样,但是那个没有经过onCreateView两次.思考?

我的activity_add_course xml被请求了......

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

     <fragment android:name="com.NsouthProductions.gradetrackerpro.AddCourse$AddCourseFragment"
         android:id="@+id/AddCourseFrag" 
         android:layout_width="match_parent"
         android:layout_height="match_parent" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

brw*_*dev 14

看起来你要两次添加片段.如果在xml中声明它,那么您也不需要以编程方式添加它.

你可以从你的Activity中删除它: onCreate()

if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new AddCourseFragment()).commit();
        }
Run Code Online (Sandbox Code Playgroud)