有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java'指定的子级已具有父级。您必须首先对子级的父级调用removeView()不知道我错在哪里

这是我的数字活动代码摘录: 注:“words”是一个字符串类型的“ArrayList”,元素范围从“1-10”到“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.'

我的理解是,我们已经声明了一个文本视图,现在我们正在循环添加'words'ArrayList的元素,并将文本视图添加到根视图。请帮帮我,我哪里做错了


共 (1) 个答案

  1. # 1 楼答案

    如果在for循环中声明TextView,则每次迭代都会向RootViewNumber添加一个新的视图实例,同时代码会尝试向引发异常的父级添加相同的视图实例

    您可以将代码编辑为:

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