在Fragment中旋转显示后恢复对象

时间:2015-10-25 19:04:36

标签: java android

我需要恢复对象(视图模型)并在旋转显示后绑定到布局。 我在onSaveInstanceState中将Object保存为Byte []。 我的问题:onCreateView在onActivityCreated之前触发,此代码binding.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);
     }

实用功能:

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();

}

1 个答案:

答案 0 :(得分:0)

将您的模型恢复代码放在' OnCreate '片段的方法。 '的 OnCreate中'在' OnCreateView '之前调用。有关Android片段的更多信息,请访问:生命周期,请检查此链接:Android Fragments' lifecycle