Hello,
Welcome to our Microsoft Q&A platform!
I made a simple demo based on the official sample activitylifecycle, and it works properly.
You can refer to the following code :
1.create a class Book
and implement Java.Lang.Object, IParcelable
public class Book: Java.Lang.Object, IParcelable
{
public string Name;
public string Author;
public string Editor;
public int Year;
public string CoverPath;
public override string ToString ()
{
return string.Format ("{0} - {1}", Name, Author);
}
[ExportField ("CREATOR")] // Need a reference to Mono.Android.Export
public static BookCreator InitializeCreator ()
{
return new BookCreator ();
}
public void WriteToParcel (Parcel dest, ParcelableWriteFlags flags)
{
dest.WriteString (Name);
dest.WriteString (Author);
dest.WriteString (Editor);
dest.WriteInt (Year);
dest.WriteString (CoverPath);
}
public int DescribeContents ()
{
return 0;
}
}
public class BookCreator : Java.Lang.Object, IParcelableCreator
{
public Java.Lang.Object CreateFromParcel(Parcel source)
{
Book book = new Book();
book.Name = source.ReadString();
book.Author = source.ReadString();
book.Editor = source.ReadString();
book.Year = source.ReadInt();
book.CoverPath = source.ReadString();
return book;
}
public Java.Lang.Object[] NewArray(int size)
{
return new Java.Lang.Object[size];
}
}
2.in MainActivity
, we just added the following code in OnCreate
and OnSaveInstanceState
:
protected override void OnSaveInstanceState (Bundle outState)
{
Book book = new Book {Name="book1", Author ="Hello", Editor= "Editor1", Year=2020 };
outState.PutParcelable("mBook",book);
Log.Debug(GetType().FullName, "Activity A - Saving instance state");
// always call the base implementation!
base.OnSaveInstanceState (outState);
}
3.method OnCreate
:
protected override void OnCreate(Bundle bundle)
{
Log.Debug(GetType().FullName, "Activity A - OnCreate");
base.OnCreate(bundle);
SetContentView (Resource.Layout.Main);
if (bundle != null)
{
Book book = (Book)bundle.GetParcelable("mBook");
Log.Debug(GetType().FullName, "Activity A - Recovered instance state");
Toast.MakeText(this,"book name: " + book.Name + " , book Author : " + book.Author, ToastLength.Short).Show();
}
And when we rotate the device to landscape
mode, the book data is preserved!
Best Regards,
Jessie Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.