Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy would I ever want `setRetainInstance(false)`? - Or - The correct way to handle device rotation
    text
    copied!<p><em>Please correct me if I'm wrong on any of this. This is a kind of clarifying question since I haven't seen it explicitly written anywhere.</em></p> <p>In Android 4, you can call <code>setRetainInstance(true)</code> on a <code>Fragment</code> so that on configuration changes (which basically means device rotation), the <code>Fragment</code> java object isn't destroyed and a new instance of it isn't created. That is, the instance is retained.</p> <p>This is much more sane and less infuriating than in Android 1-3 since you don't have to deal with <code>onRetainNonConfiguration</code><strike><code>State</code></strike><code>Instance()</code> and bundle up all your data so it can be passed to the new <code>Fragment</code> (or <code>Activity</code>) instance only to be unbundled again. It's basically what you would expect to happen, and arguably how it should have worked for <code>Activity</code>s from the beginning.</p> <p>With <code>setRetainInstance(true)</code> the view is also recreated (<code>onCreateView()</code> is called) on rotation as you would expect. And I assume (not tested) that resource resolution (<code>layout</code> vs <code>layout-land</code>) works.</p> <p>So my question is two-fold:</p> <ol> <li>Why wasn't it like this with <code>Activities</code> from the beginning.</li> <li>Why isn't this the default? Is there ever any reason why you <em>would</em> actually want your <code>Fragment</code> to be pointlessly destroyed and recreated on rotation? Because I can't think of any.</li> </ol> <h1>Edit</h1> <p>To clarify how I would do it:</p> <pre><code>class MyFragment extends Fragment { // All the data. String mDataToDisplay; // etc. // All the views. TextView mViewToDisplayItIn; // etc. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mDataToDisplay = readFromSomeFileOrWhatever(); // Ignoring threading issues for now. } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.my_fragment, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { // At this point if mViewToDisplayItIn was not null, the old one will be GC'd. mViewToDisplayItIn = view.findViewById(R.id.the_text_view); mViewToDisplayItIn.setText(mDataToDisplay); } // Optionally: @Override public void onDestroyView() { // All the view (and activity) to be GC'd. mViewToDisplayItIn = null; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload