我想知道在Android中存储复杂数据类型变量的最佳方法是什么。 onSaveInstanceState()只能用于简单的数据类型,如字符串,整数等,但如果我想保存其他内容,我该怎么办?
这些是我目前所知的方法:
我对上述任何一种方法都不满意,所以我正在寻找一种不同的,更通用的方法。例如,如果我想保存包含片段的ArrayList,我该怎么办(让我们不讨论为什么我会这样做,让我们也假装没有像碎片管理器这样的东西)。
答案 0 :(得分:0)
我相信如果你可以制作一个可分类的类,你可以在同一OnsaveInstanceState
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
try
{
outState.putParcelable("ListViewFragment", (Parcelable) mLeftMenuFragment);
outState.putParcelable("ProductsGridFragment", (Parcelable) mProductsGridFragment);
outState.putParcelable("ProductDetailsFragment", (Parcelable) mProductDetailsFragment);
outState.putParcelable("FeaturedFragment", (Parcelable) mFeaturedFragment);
outState.putParcelable("CategoryFragment", (Parcelable) mCategoryFragment);
}
catch(Exception e)
{
mLogger.error(Logger.ERROR_CODE_API, e);
}
}
按以下方式取回
if(savedInstanceState != null)
{
isFeaturedProduct = savedInstanceState.getBoolean("IsFeaturedProduct");
mLeftMenuFragment = (LeftMenuFragment) savedInstanceState.getParcelable("ListViewFragment");
mProductsGridFragment = (ProductListFragment) savedInstanceState.getParcelable("ProductsGridFragment");
mProductDetailsFragment = (ProductDetailsFragment) savedInstanceState.getParcelable("ProductDetailsFragment");
if(isFeatured)
mFeaturedFragment = (FeaturedFragment) savedInstanceState.getParcelable("FeaturedFragment");
else
mCategoryFragment = (CategoryFragment) savedInstanceState.getParcelable("CategoryFragment");
// mActionBar.setTitle(savedInstanceState.getString("ActionBarTitle"));
}
else
{
mLeftMenuFragment = new LeftMenuFragment();
mProductsGridFragment = new ProductListFragment();
mProductDetailsFragment = new ProductDetailsFragment();
if(isFeatured)
{
mFeaturedFragment = new FeaturedFragment();
}
else
{
mCategoryFragment = new CategoryFragment();
}
mIsFeaturedClicked = true;
}