【发布时间】:2012-03-31 15:19:19
【问题描述】:
我正在尝试保存和恢复由按钮表组成的视图层次结构。表格中所需的表格行数和按钮数直到运行时才知道,并且在我的Activity 的onCreate(Bundle) 方法中以编程方式添加到膨胀的xml 布局中。我的问题是:可以使用Android的默认视图保存/恢复实现来保存和恢复决赛桌吗?
下面是我当前尝试的一个示例。在初始运行时,表按预期构建。当 Activity 被销毁(通过旋转设备)时,重建后的视图只显示一个空的 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);
}
}
}
我的理解是,只要为视图分配了 ID,Android 就会保存视图的状态,并在重新创建 Activity 时恢复视图,但现在它似乎重新膨胀了 xml 布局,仅此而已。在调试代码时,我可以确认在表中的每个Button 上都调用了onSaveInstanceState(),但onRestoreInstanceState(Parcelable) 没有。
【问题讨论】: