简体   繁体   English

Android将活动状态保存在Parcelable类对象中

[英]Android save Activity state in Parcelable class object

in my application i many onSaveInstanceState in each activity and file, now after reading this link to create Parcelable class i can not use that and save into this class 在我的应用程序中,我在每个活动和文件中都有许多onSaveInstanceState ,现在在阅读了此链接以创建Parcelable类之后,我无法使用它并保存到此类中

default onSaveInstanceState is: 默认的onSaveInstanceState为:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putBoolean("IsShowingExitDialogs", mIsShowingExitDialogs);
    savedInstanceState.getInt("LastMenuItemSelected", mLastMenuItemSelected);
}

now i can not use this below line to save IsShowingExitDialogs or LastMenuItemSelected to Parcable class: 现在我不能使用此行将IsShowingExitDialogsLastMenuItemSelected保存到Parcable类:

savedInstanceState.putParcelable("IsShowingExitDialogs", mIsShowingExitDialogs);
savedInstanceState.putParcelable("IsShowingExitDialogs", mLastMenuItemSelected);

Parcelable is an interface applied on classes. Parcelable是应用于类的接口 It works for objects , whereas in your case you are trying to save an integer and a boolean , both of which are primitive types . 它适用于对象 ,而在您的情况下,您试图保存一个整数和一个布尔值 ,它们都是原始类型 If you really want to do this, you need to wrap them inside a class that implements Parcelable . 如果您确实想这样做,则需要将它们包装在实现Parcelable的类中。 Then this will work. 然后这将起作用。

EDIT: 编辑:

1. The savedInstanceState that you save in onSavedInstanceState() is returned in onCreate() when the Activity is recreated, allowing you to reuse the data that you saved previously. 1. savedInstanceState您在保存 onSavedInstanceState()在返回onCreate()Activity被重建,让您重新使用以前保存的数据。

2. You need to create a custom class MyClass extends Parcelable , implement the interface methods and save it like this: 2.您需要创建一个自定义类MyClass extends Parcelable ,实现接口方法并按如下方式保存它:

MyClass myClass = new MyClass(mIsShowingExitDialogs, mLastMenuItemSelected);
savedInstanceState.putParcelable("myClass", myClass);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM