我聲明瞭一個空的LinearLayout,在我的onCreate方法中,我調用了一個循環,該循環重複五次以膨脹另一個佈局並將其添加到我的LinearLayout中。爲什麼ProgressBar的ID需要是唯一的?
private void setupList() {
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout itemList = (LinearLayout) findViewById(R.id.itemList);
itemList.removeAllViews();
for (Category category :: categories) {
View rowView = layoutInflater.inflate(R.layout.category_row, null);
initializeRow(rowView, category.percentComplete);
itemList.addView(rowView);
}
}
然後在我的initializeRow方法中,我初始化了一個TextView和ProgressBar,它們在我剛剛膨脹的視圖中。
private void initializeRow(final View view, final int percentComplete) {
TextView topicView = ((TextView) view.findViewById(R.id.topic));
topicView.setText(category.title);
ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setMax(100);
progressBar.setProgress(percentComplete);
TextView textView = (TextView) view.findViewById(R.id.progressText);
textView.setText(percentComplete "% Complete");
}
第一次創建此活動時,進度欄和文本視圖將顯示正確的值。但是,如果我旋轉我的設備,則TextView會以正確的值顯示,但所有ProgressBars都會顯示與上一個ProgressBar對應的進度。爲什麼當onCreate最初被調用時,這種方式會起作用,但在設備旋轉後onCreate方法被調用時,這種方式不會被調用?
我意識到所有的ProgressBars都有相同的ID。但在我的代碼中,我通過使用充氣的視圖的findViewById來獲取對特定ProgressBar的引用。通過在我的initializeRow方法中調用
progressBar.setId(progressBarIds[ position ]);
,我可以通過給每個ProgressBar一個唯一的ID來實現這個工作。我很好奇,如果這種行爲是ProgressBar中某個錯誤的結果,或者有一些關於我不明白的layoutInflaters或ProgressBars的規則。