android – 从已保存状态恢复视图层次结构不会恢复以编程方式添加的视图
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了android – 从已保存状态恢复视图层次结构不会恢复以编程方式添加的视图,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2322字,纯文字阅读大概需要4分钟。
内容图文
![android – 从已保存状态恢复视图层次结构不会恢复以编程方式添加的视图](/upload/InfoBanner/zyjiaocheng/709/6910629b3b0948b1a4ec0a779efde8f8.jpg)
我试图保存和恢复由按钮表组成的视图层次结构.表中所需的表行和按钮的数量在运行时才知道,并且在我的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)不是.
解决方法:
在搜索了Activity,View和ViewGroup的源代码之后,我了解到,每次调用onCreate(Bundle)时,必须以编程方式添加以编程方式添加的视图并为其分配相同的ID.无论是第一次创建视图还是在销毁活动后重新创建视图,都是如此.然后在调用Activity.onRestoreInstanceState(Bundle)期间恢复以编程方式添加的视图的已保存实例状态.上面代码的最简单答案就是删除对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 – 从已保存状态恢复视图层次结构不会恢复以编程方式添加的视图全部内容,希望文章能够帮你解决android – 从已保存状态恢复视图层次结构不会恢复以编程方式添加的视图所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。