I'm confused about the best practice for saving the states of Views that live inside of fragments in Android.
I thought that setRetainInstance(true)
would do the trick; however, while this does retain the old global View
references declared in the Fragment
, those Views will not be used when inflating the layout. Thus, I have to manually transfer the properties from the old global View references to the new Views in the inflated layout. See the code below for how I'm doing this.
public static class MyFragment extends Fragment {
// I need to save the state of two views in the fragment
ProgressBar mProgress;
TextView mText;
@Override public void onCreate(Bundle savedInstanceState) {
// savedInstanceState == null if setRetainInstance == true
super.onCreate(savedInstanceState);
// Retain the instance between configuration changes
setRetainInstance(true);
}
@Override public View onCreateView(LayoutInflater i, ViewGroup c, Bundle b) {
// Inflate xml layout for fragement (orientation dependent)
View v = i.inflate(R.layout.fragment_main, c, false);
// Grab Views from layout
ProgressBar tmpProgress = (ProgressBar) v.findViewById(R.id.progress);
TextView tmpText = (TextView) v.findViewById(R.id.text);
// If View References exist, transfer state from previous Views
if(mProgress != null){
tmpProgress.setProgress(mProgress.getProgress());
tmpText.setText(mText.getText());
}
// Replace View references
mProgress = tmpProgress;
mText = tmpText;
return v;
}
}
It's my feeling that setRetainInstanceState(true)
should mainly be used for keeping a fragment alive so that background processes can maintain a connection to it. If that's the case should I not be using this method to retain the states of my View
s?
More specifically:
- if
setRetainInstanceState
istrue
, is the above code the best way to retain theView
states between orientation calls? - If I'm not interacting with background tasks, should I just use
setRetainInstanceState(false)
and useBundle
s to maintain the View states? (Note: bundles cannot be used ifsetRetainInstance == true
)