Ste*_*bbi 3 android bundle android-fragments
我有一个片段,似乎在屏幕旋转配置更改后会自动恢复状态。每当旋转屏幕时,我都可以在日志中验证片段中是否调用了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
}
Run Code Online (Sandbox Code Playgroud)
这可能与我的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();
}
Run Code Online (Sandbox Code Playgroud)