Fragment automatically saving and restoring state of EditTexts

邮差的信 提交于 2019-12-21 20:48:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!