我试图了解使用片段保存和恢复状态的过程。我用它创建了滑动导航菜单。
在其中一个片段中有这样的代码:
public class FifthFragment extends Fragment {
CheckBox cb;
View view;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fifth_layout, container, false);
cb = (CheckBox) view.findViewById(R.id.checkBox);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore save state
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save state
}
}
Run Code Online (Sandbox Code Playgroud)
例如,我想在用户退出片段之前保存复选框的状态,并在再次创建片段时恢复它。如何实现这一目标?
编辑:
根据 raxellson 的回答,我已将片段更改为:
public class FifthFragment extends Fragment {
private static final …Run Code Online (Sandbox Code Playgroud)