java - '指定的 child 已经有一个 parent 。您必须首先在子级的父级上调用removeView() .' and not sure where I' m 错误

标签 java for-loop arraylist textview android-linearlayout

这是我的 Numbers Activity 的代码摘录: 注意:“words”是一个 String 类型的“ArrayList”,其元素范围为“One-Ten”,“size=9”。

// Find the root view of the Numbers activity
   LinearLayout rootViewNumbers = findViewById(R.id.root_numbers_LL);

// creating a text view to assign the words to it
   TextView wordView = new TextView(this);

for(int i = 0; i <= words.size(); i++) {

            // setting the text to text view by using the 'i' for index position iterator
            wordView.setText(words.get(i));

            // setting the text view to the root view
            rootViewNumbers.addView(wordView);
        }

当我运行应用程序时,我收到错误

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

我的理解是,我们已经声明了一个 TextView ,现在我们正在循环迭代以添加“words”ArrayList 的元素,并将 TextView 添加到 Root View 。请帮助我我哪里出错了!!

最佳答案

如果您在 for 循环内声明 TextView,则每次迭代都会向 rootViewNumbers 添加一个新的 View 实例,而您的代码会尝试向引发异常的父级添加相同的 View 实例。

您可以将代码编辑为:

 TextView wordView;

 for(int i = 0; i <= words.size(); i++) {

        wordView = new TextView(this)

        // setting the text to text view by using the 'i' for index position iterator
        wordView.setText(words.get(i));

        // setting the text view to the root view
        rootViewNumbers.addView(wordView);
    }

关于java - '指定的 child 已经有一个 parent 。您必须首先在子级的父级上调用removeView() .' and not sure where I' m 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60990391/

相关文章:

java - 使用正则表达式提取字符串

Java (Eclipse) - 条件编译

windows - 如何在批处理文件脚本中循环打印程序的返回值?

java - 仅将文件中的特定文本添加到数组列表

Java Swing - PDF 缩略图查看器

java - 为什么我们要写Synchronized(ClassName.class)

list - 循环遍历 Perl 中的列表

c++ - 如何读取多行输入?

java - 驱动程序类中的数组列表方法不起作用

java - 我们如何删除 arrayList 中的多个值?