这是我的 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/