问题
I have a fragment that seems to be automatically restoring state over a screen rotation configuration change. I can verify in the logs that onCreatView is called in the fragment whenever the screen is rotated. Despite calling down to applyDefaults(), the draft entries that the user made are retained when the screen rotates and onCreateView() is called.
My understanding is that I would have to save state in onSaveInstanceState() and restore it in onCreateView(), but that doesn't seem to be the case. Can someone explain?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "onCreateView()");
View view = inflater.inflate(R.layout.fragment_email_entry, container, false);
m_hostNameEditText = (EditText) view.findViewById(R.id.hostNameEditText);
// set reference for other fields
applyDefaultsForNewEmailAccount();
return view;
}
private void applyDefaults() {
m_hostNameEditText.setText("");
// set other defaults
}
It may have to do with the fact that my Activity inherits from SingleFragmentActivity, so perhaps it sees that the fragment is already in the view. Still, we know that Fragment.onCreateView() is being called.
public abstract class SingleFragmentActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_fragment_activity);
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.single_frame_container);
if (fragment == null) {
fragment = createFragment();
fragmentManager.beginTransaction()
.add(R.id.single_frame_container, fragment)
.commit();
}
}
public abstract Fragment createFragment();
}
回答1:
Just like an activity, a fragment will automatically save the data of any fragment View component in the Bundle by the View component’s id. And just like in the activity, if you do implement the onSaveInstanceState( ) method make sure you add calls to the super.onSaveInstanceState( ) methods so as to retain this automatic save of View data feature.
source
来源:https://stackoverflow.com/questions/24553634/fragment-automatically-saving-and-restoring-state-of-edittexts