gpt4 book ai didi

android - 旋转设备时 RecyclerView/MapView 崩溃

转载 作者:太空狗 更新时间:2023-10-29 16:32:11 37 4
gpt4 key购买 nike

我有一个 Android.Support.V4.Fragment,其中包含一个 MapView 和一个 RecyclerView。这些是 Fragment 中的独立 View 。

设备旋转时应用崩溃:

Android.OS.BadParcelableException: ClassNotFoundException when unmarshalling: android.support.v7.widget.RecyclerView$SavedState

我按照文档的要求将生命周期方法传递给 MapView:

private MapView mapView;
private RecyclerView myRecyclerView;
private RecyclerView.LayoutManager myLayoutManager;

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView(inflater, container, savedInstanceState);

myRecyclerView = myRootView.FindViewById<RecyclerView>(Resource.Id.myRecyclerView);
myLayoutManager = new LinearLayoutManager(activity, LinearLayoutManager.Horizontal, false);
myRecyclerView.SetLayoutManager(myLayoutManager);
myRecyclerAdapter = ...
myRecyclerView.SetAdapter(myRecyclerAdapter);

mapView.OnCreate(savedInstanceState);
}


public override void OnSaveInstanceState(Bundle outState)
{
...
if (mapView != null) mapView.OnSaveInstanceState(outState);
base.OnSaveInstanceState(outState);
}

如果我从 AXML 中删除 RecyclerView,它会正确旋转,如果我包含它,应用程序会在 mapView.OnCreate(savedInstanceState) 崩溃,这是为什么?

最佳答案

对于搜索并遇到相同问题的任何人。 This is the solution , 这似乎是一个 2 年前的错误。

I was able to get around it by saving the MapView's saved state on a separate Bundle and then adding it to the outgoing saved state bundle. Then in onCreate(), I would just grab the MapView's saved state from the incoming one and pass it into its onCreate() method, thus stopping the crashes.

在我的例子中,我是这样实现的:

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
base.OnCreateView(inflater, container, savedInstanceState);

myRecyclerView = myRootView.FindViewById<RecyclerView>(Resource.Id.myRecyclerView);
myLayoutManager = new LinearLayoutManager(activity, LinearLayoutManager.Horizontal, false);
myRecyclerView.SetLayoutManager(myLayoutManager);
myRecyclerAdapter = ...
myRecyclerView.SetAdapter(myRecyclerAdapter);

Bundle mapViewSavedInstanceState = savedInstanceState != null ? savedInstanceState.GetBundle("mapViewSaveState") : null;
mapView.OnCreate(mapViewSavedInstanceState);
}


public override void OnSaveInstanceState(Bundle outState)
{
if (mapView != null)
{
Bundle mapViewSaveState = new Bundle(outState);
outState.PutBundle("mapViewSaveState", mapViewSaveState);
mapView.OnSaveInstanceState(outState);

}
base.OnSaveInstanceState(outState);
}

关于android - 旋转设备时 RecyclerView/MapView 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36131256/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com