Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在片段中旋转显示后还原对象_Java_Android - Fatal编程技术网

Java 在片段中旋转显示后还原对象

Java 在片段中旋转显示后还原对象,java,android,Java,Android,我需要恢复对象(视图模型)并在旋转显示后绑定到布局。 我将对象保存到onSaveInstanceState中的字节[]。 我的问题:onActivityCreated之前触发onCreateView,此代码绑定。setViewModel(templateViewModel)绑定为Null。如何保存templateViewModel @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, B

我需要恢复对象(视图模型)并在旋转显示后绑定到布局。 我将对象保存到onSaveInstanceState中的字节[]。 我的问题:onActivityCreated之前触发onCreateView,此代码绑定。setViewModel(templateViewModel)绑定为Null。如何保存templateViewModel

 @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