我有一个带有以编程方式添加子项的 LinearLayout:
for (int i = 0; i < answers.size(); i++) {
final AnswerView answerView = new AnswerView(getContext(), i);
addView(answerView);
}
然后我试图访问随机孩子:
private void updateOpenAnswer() {
new AsyncTask<Void, Void, Integer>() {
@Override
protected Integer doInBackground(Void... voids) {
return API.getOpenAnswer();
}
@Override
protected void onPostExecute(Integer answerIndex) {
super.onPostExecute(answerIndex);
Log.i(TAG, "Child count: " + getChildCount());
if (answerIndex != -1) {
Log.i(TAG, "Open answer: " + answerIndex);
final AnswerView answerView = (AnswerView) getChildAt(answerIndex);
if (answerView != null) {
answerView.setAnswerOpen(true);
} else {
Log.e(TAG, "Null at " + answerIndex);
}
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
updateOpenAnswer 在 runnable 中每秒调用一次。对于 updateOpenAnswer 的某些调用,getChildAt 返回 null 并且 getChildCount 返回 0!例如,2 和 3 为 null,0、1、4、5 为非 null。2 和 3 的观点确实存在,我看到了。为什么它返回null?