我有一个活动,可以像这样在onCreate中加载一个片段:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new FragmentName());
}
private void loadFragment(Fragment fragment) {
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(R.id.frag_lay, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
而且我正在尝试保存和恢复这样加载的片段的状态:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
spinner.setSelection(savedInstanceState.getInt("spinner"));
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("spinner", spinner.getSelectedItemPosition());
}
发生的事情是我正确地存储了微调器的位置,但是无论如何我都重新创建了微调器,并且即使我选择了保存的微调器,其位置也是默认位置。 我不太确定为什么会这样,有人可以帮忙吗?
编辑
我在这里设置微调器:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_campus, container, false);
...
setupSpinner();
return view;
}
private void setupSpinner() {
ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(this.getActivity(),
R.array.array_spinner,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter)
}
编辑2
我做了更多尝试。我举杯敬酒来展示这样的情况:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
Toast toast = Toast.makeText(getActivity(), "saved !=", Toast.LENGTH_SHORT);
toast.show();
}else{
Toast toast = Toast.makeText(getActivity(), "saved ==", Toast.LENGTH_SHORT);
toast.show();
}
}
当我尝试在模拟器上运行此代码时,会发生这种情况:当我首次启动该应用程序时,它将进入else语句(应该正确)。当我更改方向时,会同时显示两个祝酒词(很明显,我先在onSaveInstanceState中保存了一些东西),这是不对的。为什么会这样?
答案 0 :(得分:0)
在活动中更改此行:
loadFragment(new FragmentName());
对此:
if (savedInstanceState == null) {
loadFragment(new FragmentName());
}
FragmentManager将为您自动保存和还原活动中的片段,这是保存和还原这些片段的状态的同一过程的一部分。但是,现在,每次重新创建活动时,您都将旧片段扔掉,并用新片段替换。