'指定的孩子已经有一个父母。您必须先在孩子的父母上调用removeView()。”不确定我在哪里错

问题描述 投票:0回答:1

这是我的Numbers活动代码摘录:注意:'words'是String类型的'ArrayList',其elemts范围从'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);
        }

[当我运行该应用程序时,我得到的错误是

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

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

java for-loop arraylist textview android-linearlayout
1个回答
0
投票

如果在for循环中声明TextView,则将在每次迭代中向rootViewNumbers添加一个新的视图实例,而您的代码尝试将同一视图实例添加到引发异常的父视图中。

您可以将代码编辑为:

 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);
    }
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.