【问题标题】:Specified child has already a parent error指定的孩子已经有一个父错误
【发布时间】:2015-04-24 10:45:33
【问题描述】:

我收到了这个错误

指定的孩子已经有一个父母。您必须调用 removeView() 首先是孩子的父母

这是代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.categorylayout);

    LinearLayout main = (LinearLayout)findViewById(R.id.main_layout);
    View view = getLayoutInflater().inflate(R.layout.categoryeditor, main, true);
    main.addView(view);
}

我收到此错误是因为我在这里传递了true

inflate(R.layout.categoryeditor, main, true);  

我的问题:

The specified child already has a parent父母在哪里?

【问题讨论】:

    标签: android


    【解决方案1】:
      View view = getLayoutInflater().inflate(R.layout.categoryeditor, main,true);
    

    您已经通过最后两个参数提供了父级。传递true 将告诉Android 将膨胀视图添加到main。这样你就可以摆脱

      main.addView(view);
    

    另请注意,在您的情况下,返回的 View 不是膨胀的,而是它的父级

    【讨论】:

    • 1.那么最后的true意味着main是父视图,view是父视图?对 2. 如果最后一个参数是false,那么视图不是父视图?对吧?
    • add it manually to main 抱歉,请告诉我应该添加什么?
    • 是的,抱歉。如果您将false 作为第三个参数传递,则必须调用main.addView(view);
    【解决方案2】:

    替换

    View v = inflater.inflate(R.layout.camera_fragment, main, true);
    

    View v = inflater.inflate(R.layout.camera_fragment, main, false);
    

    【讨论】:

    • 非常感谢您的回答。但我真的很想根据我的代码知道parent 是什么。反正已经回答了。
    【解决方案3】:

    您的主要视图是父视图。在这种情况下,您的最后一个参数告诉附加到父级

    View view = getLayoutInflater().inflate(R.layout.categoryeditor, main,true);
    

    【讨论】:

      【解决方案4】:

      只需阅读该方法的文档

      参数: 资源 ID 用于加载 XML 布局资源(例如,R.layout.main_page)

      root 作为生成层次结构的父级的可选视图(如果 attachToRoot 为 true),或者只是为返回的层次结构的根提供一组 LayoutParams 值的对象(如果 attachToRoot 为错误。)

      attachToRoot 膨胀的层次结构是否应该附加到根参数?如果为 false,则 root 仅用于为 XML 中的根视图创建正确的 LayoutParams 子类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-19
        • 1970-01-01
        • 2017-05-21
        • 2021-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多