我试图保存和恢复由按钮表组成的视图层次结构.表中所需的表行和按钮的数量在运行时才知道,并且在我的Activity的onCreate(Bundle)方法中以编程方式添加到膨胀的xml布局中.我的问题是:可以使用Android的默认视图保存/恢复实现来保存和恢复最终表吗?
我目前的尝试的一个例子如下.在初始运行时,表按预期构建.当活动被销毁时(通过旋转设备),重建的视图仅显示没有子项的空TableLayout.
setContentView(int)中引用的xml文件包括添加按钮的空TableLayout.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup this activity's view.
setContentView(R.layout.game_board);
TableLayout table = (TableLayout) findViewById(R.id.table);
// If this is the first time building this view, programmatically
// add table rows and buttons.
if (savedInstanceState == null) {
int gridSize = 5;
// Create the table elements and add to the table.
int uniqueId = 1;
for (int i = 0; i < gridSize; i++) {
// Create table rows.
TableRow row = new TableRow(this);
row.setId(uniqueId++);
for (int j = 0; j < gridSize; j++) {
// Create buttons.
Button button = new Button(this);
button.setId(uniqueId++);
row.addView(button);
}
// Add row to the table.
table.addView(row);
}
}
}
我的理解是,Android会保存视图状态,只要它们分配了ID,并在重新创建活动时恢复视图,但现在它似乎重新定义了xml布局,仅此而已.在调试代码时,我可以确认在表中的每个Button上调用onSaveInstanceState(),但是onRestoreInstanceState(Parcelable)不是.