Java 在片段中旋转显示后还原对象
我需要恢复对象(视图模型)并在旋转显示后绑定到布局。 我将对象保存到onSaveInstanceState中的字节[]。 我的问题:onActivityCreated之前触发onCreateView,此代码绑定。setViewModel(templateViewModel)绑定为Null。如何保存templateViewModelJava 在片段中旋转显示后还原对象,java,android,Java,Android,我需要恢复对象(视图模型)并在旋转显示后绑定到布局。 我将对象保存到onSaveInstanceState中的字节[]。 我的问题:onActivityCreated之前触发onCreateView,此代码绑定。setViewModel(templateViewModel)绑定为Null。如何保存templateViewModel @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, B
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TemplateFragmentRecyclerViewBinding binding = TemplateFragmentRecyclerViewBinding.inflate(inflater, container, false);
binding.setViewModel(templateViewModel);
binding.executePendingBindings();
return binding.getRoot();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
byte[] data =savedInstanceState.getByteArray(getString(R.string.templateViewModelData));
//Serialize
templateViewModel = (TemplateViewModel) Parcel.convertFromBytes(data);
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
byte[] data = Parcel.convertToBytes(templateViewModel);
state.putByteArray(getString(R.string.templateViewModelData), data);
}
Utils功能:
public static byte[] convertToBytes(Object object) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(object);
return bos.toByteArray();
}
public static Object convertFromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInput in = new ObjectInputStream(bis);
return in.readObject();
}
将模型还原代码放入片段的“OnCreate”方法中OnCreate”在“OnCreateView”之前调用。有关Android片段生命周期的更多信息,请查看此链接:No this not work'd。OnCreate只调用一次。后来只调用OnCreateView