从已保存状态还原视图层次结构不会还原以编程方式添加的视图

hap*_*ude 12 layout android view

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

我目前的尝试的一个例子如下.在初始运行时,表按预期构建.当活动被销毁时(通过旋转设备),重建的视图仅显示TableLayout没有子项的空.

引用的xml文件setContentView(int)包括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);
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的理解是,Android的,只要他们有分配给他们的ID保存视图状态,而当活动重新恢复的意见,但现在它似乎reinflate的XML布局,仅此而已.在调试代码时,我可以确认在表中onSaveInstanceState()每个都调用Button了,但是onRestoreInstanceState(Parcelable)没有.

hap*_*ude 12

通过对源代码的搜索后Activity,ViewViewGroup,我才知道,编程方式添加的意见必须以编程方式添加和分配相同的ID每次onCreate(Bundle)被调用.无论是第一次创建视图还是在销毁活动后重新创建视图,都是如此.然后在调用期间恢复以编程方式添加的视图的已保存实例状态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);
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的:框架保存并恢复每个视图的状态,但它不保存存在的视图.这就是为什么你不得不调用`setContentView()`而不管`savedInstanceState`是否为null,同样你必须在`onCreate()`(或`onCreateView()`中为片段创建任何动态视图).请注意,如果稍后添加视图(例如,在`onStart()`中),则为了恢复其内容为时已晚. (4认同)