【问题标题】:Why does .addView throw this parent/child exception?为什么 .addView 会抛出这个父/子异常?
【发布时间】:2015-05-23 22:29:38
【问题描述】:

你好!
我正在尝试在我的主要活动中的 LinearLayout 内创建动态 TextView。该程序(应该是)根据需要将 TextView 从resultrow XML 推送到activity_fivethreeone XML。 parentLayout.addView(textView); 行抛出此错误;

The specified child already has a parent. You must call removeView() on the child's parent first.

我尝试了类似问题的答案,但没有成功。
Fragments - The specified child already has a parent. You must call removeView() on the child's parent first
Call removeView() on the child's parent first


类:

try {
    LinearLayout parentLayout = (LinearLayout)findViewById(R.id.linLayout);
    LayoutInflater layoutInflater = getLayoutInflater();
    View view;
    for(int counter=0;counter<=theWeeksList.size();counter++){
        view = layoutInflater.inflate(R.layout.resultrow, parentLayout, false);
        TextView textView = (TextView)view.findViewById(R.id.resultRow);
        textView.setText(theWeeksList.get(counter));
        parentLayout.addView(textView);
    }
}

我尝试使用removeView(),但无法坚持使用。

任何帮助将不胜感激!
谢谢!

【问题讨论】:

  • 嘿不公平!!!我先回答!

标签: java android layout android-studio


【解决方案1】:

textView 已经作为父 view,事实上你可以通过 findViewById 成功找到它。所以这一行:

parentLayout.addView(textView);

导致异常。您可能想将view 添加到parentLayout

parentLayout.addView(view);

由于刚刚创建,它没有父级,可以添加为子级

【讨论】:

  • 谢谢!!从下午 4 点开始我就一直在拔头发(这里快到午夜了)。
【解决方案2】:

您正在尝试添加一个已经属于现有ViewGroupEditText

删除线

parentLayout.addView(textView);

来自您的代码。你不需要这样做。替换为

parentLayout.addView(view);

【讨论】:

  • 非常感谢!我喜欢/讨厌它这么小!
  • @jackEarlyDays:嘿,很抱歉这么晚才回复……没问题,我们都在这里互相帮助。顺便说一句,我先回答了。我认为我的答案应该被标记为正确的唯一公平:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2010-11-06
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多