Why is my onCreateView method being called twice?

久未见 提交于 2019-12-07 09:56:49

问题


While debugging another issue, I realized that the onCreateView method of one of my activities was being called twice. I'm new to programming and I don't fully understand how android calls these methods when the activity loads, but it doesn't seem right to me that it would be called twice. Eliminating most of my code, I still see my System.out message twice.

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;
        }       
    }
}

This is almost exactly like my main activity implementation, but that one doesn't go through onCreateView twice. Thoughts?

My activity_add_course xml was requested...

<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>

回答1:


Looks like you're adding the fragment twice. If you declare it in the xml then you don't need to add it programmatically as well.

You can remove this from your Activity's onCreate():

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


来源:https://stackoverflow.com/questions/22926393/why-is-my-oncreateview-method-being-called-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!