gpt4 book ai didi

android - 从已保存状态恢复 View 层次结构不会恢复以编程方式添加的 View

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:41:37 24 4
gpt4 key购买 nike

我正在尝试保存和恢复由按钮表组成的 View 层次结构。表中所需的表行数和按钮数直到运行时才知道,并以编程方式添加到我的 ActivityonCreate(Bundle) 方法中的膨胀 xml 布局.我的问题是:是否可以使用 Android 的默认 View 保存/恢复实现来保存和恢复最终表?

我当前尝试的示例如下。在初始运行时,该表按预期构建。当 Activity 被销毁(通过旋转设备)时,重建的 View 仅显示一个没有子项的空 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 会保存 View 的状态,只要它们有分配给它们的 ID,并在重新创建 Activity 时恢复 View ,但现在它似乎重新膨胀了 xml 布局,仅此而已。调试代码时,我可以确认 onSaveInstanceState() 在表中的每个 Button 上被调用,但 onRestoreInstanceState(Parcelable) 没有。

最佳答案

翻遍了ActivityViewViewGroup的源码,了解到以编程方式添加的 View 必须以编程方式添加和赋值每次调用 onCreate(Bundle) 时使用相同的 ID。不管是第一次创建 View ,还是销毁Activity后重新创建 View 都是如此。然后在调用 Activity.onRestoreInstanceState(Bundle) 期间恢复以编程方式添加的 View 的已保存实例状态。上面代码的最简单答案就是删除对 savedInstanceState == null 的检查。

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);

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 - 从已保存状态恢复 View 层次结构不会恢复以编程方式添加的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9714265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com