我尝试在 Java 中动态添加一些 TextView。我假设当我想使用setText()
方法时,我应该早先将我的 Java 的 TextView 对象与 XML 的 TextView 连接起来——我使用setId()
.
最后,我在使用setId()
.
我的代码:
TextView[] tvQuestion = new TextView[numberOfQuestions];
TextView[] tvAnswer1 = new TextView[numberOfQuestions];
TextView[] tvAnswer2 = new TextView[numberOfQuestions];
TextView[] tvAnswer3 = new TextView[numberOfQuestions];
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
for (int i = 0; i < numberOfQuestions; i++) {
tvQuestion[i].setId(View.generateViewId()); // NullPointerException!
tvAnswer1[i].setId(View.generateViewId());
tvAnswer2[i].setId(View.generateViewId());
tvAnswer3[i].setId(View.generateViewId());
tvQuestion[i].setLayoutParams(params);
tvAnswer1[i].setLayoutParams(params);
tvAnswer2[i].setLayoutParams(params);
tvAnswer3[i].setLayoutParams(params);
tvQuestion[i].setText(question[i]);
tvAnswer1[i].setText(option1[i]);
tvAnswer2[i].setText(option2[i]);
tvAnswer3[i].setText(option3[i]);
layAll.addView(tvQuestion[i]);
layAll.addView(tvAnswer1[i]);
layAll.addView(tvAnswer2[i]);
layAll.addView(tvAnswer3[i]);
}
编辑:
解决方案:Philipp Jahoda 的帖子。