gpt4 book ai didi

android - fragment 不会在方向改变时持续存在

转载 作者:太空狗 更新时间:2023-10-29 15:03:55 29 4
gpt4 key购买 nike

我使用下拉导航,由于一些主题问题,我使用了 Spinner。我使用以下方法设置 Actionbar:

public void setupActionBar() {
Spinner navSpinner = new Spinner(new ContextThemeWrapper(this, R.style.Theme_Apptheme_Widget_ActionBarSpinner));
navSpinner.setSelection(getSharedPreferences(APP_NAME, MODE_PRIVATE).getInt(SELECTED_POSITION, 0));
Log.d(getClass().getName(), navSpinner.getSelectedItemPosition() + "");
navSpinner.setAdapter(new ActionBarSpinnerAdapter(getActionBar().getThemedContext(), dataSource.getAllShoppingLists()));
navSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (position < dataSource.getAllShoppingLists().size()) {
if(fragmentManager.findFragmentByTag("shoppinglist" + position) == null) {
ShoppingListFragment shoppingListFragment = ShoppingListFragment.
newInstance(dataSource.getShoppingListForPosition(position).getId());
fragmentTransaction.replace(R.id.container, shoppingListFragment, "shoppinglist" + position);
}
} else if (position == dataSource.getAllShoppingLists().size()) {
if(fragmentManager.findFragmentByTag("shoppinglistmanager") == null) {
ShoppingListManagerFragment shoppingListFragment = ShoppingListManagerFragment.newInstance();
fragmentTransaction.replace(R.id.container, shoppingListFragment, "shoppinglistmanager");
}
}
fragmentTransaction.commit();
SharedPreferences preferences = getSharedPreferences(APP_NAME, MODE_PRIVATE);
preferences.edit().putInt(SELECTED_POSITION, position).commit();
}
});

getActionBar().setCustomView(navSpinner);
}

我在 FragmentonCreate() 上调用了 setRetainInstance(true);,但 Fragment 仍然没有被持久化。我通过拥有和 EditText 并向其输入文本来检查这一点。为什么会这样?

最佳答案

您需要为EditText设置一个标识符,以便Android系统保存和恢复 View 状态。

来自 docs :

Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.

如果您正在使用布局文件,请通过属性 android:id 指定它,或者如果您正在使用 API 创建 EditText,则使用 View.setId .

关于android - fragment 不会在方向改变时持续存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23726545/

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