android-片段自动保存和恢复EditTexts的状态

我有一个片段,似乎在屏幕旋转配置更改后会自动恢复状态.每当旋转屏幕时,我都可以在日志中验证片段中是否调用了onCreatView.尽管调用了applyDefaults(),但当屏幕旋转并调用onCreateView()时,用户所做的草稿条目将保留.

我的理解是,我必须将状态保存在onSaveInstanceState()中,然后在onCreateView()中进行还原,但这似乎并非如此.有人可以解释吗?

@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
}

这可能与我的Activity继承自SingleFragmentActivity的事实有关,因此也许它看到该片段已在视图中.不过,我们知道正在调用Fragment.onCreateView().

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();
}

解决方法:

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

上一篇:深入理解java虚拟机(13):类加载系统案例-OSGI灵活的类加载架构


下一篇:OSGi无头运行在Linux上-org.eclipse.core.runtime无法获取应用程序服务