title: OnSaveInstaceState and dynamically generated layouts and fragments
body: <p>On this <a href="http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)" rel="nofollow">documentation page about onSaveInstanceState</a> I read:</p>
  
  <blockquote>
    <p>The default implementation takes care of most of the UI per-instance
    state for you by calling onSaveInstanceState() on each view in the
    hierarchy that has an id, ...</p>
  </blockquote>
  
  <p>and interpret as:</p>
  
  <ul>
  <li><p>if I generate a <code>LinearLayout L</code> containing an <code>ImageView I</code> and a <code>Fragment F</code></p></li>
  <li><p>and I assign an ID to <code>L</code>, <code>I</code>, and <code>L</code></p></li>
  <li><p>then <code>L</code>, <code>I</code>, and <code>F</code> are saved when <code>onSaveInstanceState(.)</code> is called</p></li>
  </ul>
  
  <p>However, this does not happen: all the dynamically generated views are not restored if I terminate and re-open the app.</p>
  
  <p>The code follows:</p>
  
  <pre><code>PacketEditorFragment packetFragment = PacketEditorFragment.newInstance();
  ViewGroup vg = (ViewGroup) findViewById(R.id.packetFragmentContainer);
  
  LinearLayout linearLayout = new LinearLayout(this);
  
  int layoutId = IDS++;
  String fragmentTag = FRAGMENT_TAG + layoutId;
  
  linearLayout.setId(layoutId);
  linearLayout.setOrientation(LinearLayout.HORIZONTAL);
  
  vg.addView(linearLayout);
  
  DeleteImageView deleteFragmentIV = new DeleteImageView(this, layoutId, fragmentTag);
  deleteFragmentIV.setId(layoutId);
  deleteFragmentIV.setOnClickListener(this);
  deleteFragmentIV.setImageResource(R.mipmap.ic_delete);
  linearLayout.addView(deleteFragmentIV);
  
  getSupportFragmentManager().beginTransaction()
                  .add(linearLayout.getId(), packetFragment, fragmentTag)
                  .commit();
  </code></pre>
  
  <p>Is that piece of documentation valid also for <code>View</code>s that are generated dinamically? </p>
  
  <p>There is another point which is a little obscure to me: What about the <code>Fragment</code>, that has not an ID (it is added using a <code>String tag</code>). Should I save and restore its state programmatically? The <code>DeleteImageView</code> stores a reference to a <code>Fragment</code> instance and deletes it in the <code>OnClick</code> listener method. </p>
  
  <p>I have seen that there is way to restore a given instance of a fragment, but is it possible to have this behaviour for free? Even if they are generated dynamically, they are still part of the view hierarchy of the activity.</p>