【问题标题】:Why is my onCreateView method being called twice?为什么我的 onCreateView 方法被调用了两次?
【发布时间】:2016-01-25 14:58:37
【问题描述】:

在调试另一个问题时,我意识到我的一个活动onCreateView方法被调用了两次。我是编程新手,我不完全理解 androidactivity 加载时如何调用这些方法,但在我看来它不会被调用两次。消除了我的大部分代码,我仍然看到我的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;
        }       
    }
}

这与我的主要活动实现几乎一模一样,但不会通过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>

【问题讨论】:

  • 你能分享你的activity_add_course布局文件吗?
  • @adavis ,我已经添加了布局文件。这是因为布局文件基本上调用了我的片段类吗?我应该如何阻止它被调用两次?
  • 看起来您添加了两次片段。如果您在 xml 中声明它,那么您也不需要以编程方式添加它。
  • @adavis ,嗯,我应该从代码的哪一部分中删除它?如何在不调用我的片段两次的情况下处理 null savedInstanceState?抱歉,我仍在努力掌握其中的一些基础知识。

标签: android android-activity oncreate


【解决方案1】:

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

你可以从你的Activity的onCreate()删除这个:

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

【讨论】:

  • 谢谢。在这里写了很长的问题,终于推断出saveInstanceState的条件代码是为了保证fragment被充气。但是由于主布局无论如何都会对其进行膨胀,因此不需要此代码。我希望没有其他副作用。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-02
  • 2011-09-04
  • 2011-01-20
  • 1970-01-01
相关资源
最近更新 更多