为什么我的onCreateView方法被调用两次? [英] Why is my onCreateView method being called twice?

查看:553
本文介绍了为什么我的onCreateView方法被调用两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这几乎与我的主要活动实现完全相同,但是不会两次执行onCreateView.有想法吗?

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

我的 activity_add_course xml已被请求...

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>

推荐答案

好像您将片段添加了两次.如果您在xml中声明它,则也不需要以编程方式添加它.

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.

您可以从活动的 onCreate()删除:

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

这篇关于为什么我的onCreateView方法被调用两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆