gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:50 25 4
gpt4 key购买 nike

我有一个 fragment 似乎在屏幕旋转配置更改时自动恢复状态。我可以在日志中验证,只要屏幕旋转,就会在 fragment 中调用 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 已经在 View 中。不过,我们知道正在调用 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

关于android - Fragment自动保存和恢复EditTexts的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24553634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com