在旋转和返回时恢复地图视图的状态



背景

我有一个更大的应用程序,其中我有几个新的谷歌地图API的问题。我试着用另一个问题来描述它,但由于它看起来太复杂了,我决定开始一个尽可能简单的新项目,并尝试重现问题。就是这样。

情况

我正在使用Fragments,并希望将MapView放入其中。我不想使用MapFragment。我准备的示例项目可能不是很漂亮,但我试图让它尽可能简单,它必须包含原始应用程序中的一些元素(再次简化(。我有一个Activity和我的自定义Fragment,其中有MapView,是通过程序添加的。Map包含一些点/Markers。单击Marker后,会显示InfoWindow,单击它会在内容中显示下一个Fragment(具有replace()功能(。

问题

我有两个问题:

  1. 当显示带有MarkersMap时,屏幕旋转会导致我的自定义MyMapPoint类出现Class not found when unmarshalling错误——我不知道为什么以及这意味着什么。

  2. 我单击Marker,然后单击InfoWindow。之后,我按下硬件后退按钮。现在我可以看到Map,但没有Markers,中心在0,0点。

代码

主要活动

public class MainActivity extends FragmentActivity {
    private ArrayList<MyMapPoint> mPoints = new ArrayList<MyMapPoint>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     
        if (savedInstanceState == null) {
            mPoints.add(new MyMapPoint(1, new LatLng(20, 10), 
                "test point", "description", null));            
            mPoints.add(new MyMapPoint(2, new LatLng(10, 20), 
                "test point 2", "second description", null));
            Fragment fragment = MyMapFragment.newInstance(mPoints);
            getSupportFragmentManager().beginTransaction()
                .add(R.id.contentPane, fragment).commit();
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/contentPane"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

map_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <com.google.android.gms.maps.MapView
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

MyMapFragment

public class MyMapFragment extends Fragment implements
    OnInfoWindowClickListener {
    public static final String KEY_POINTS = "points";
    private MapView mMapView;
    private GoogleMap mMap;
    private HashMap<MyMapPoint, Marker> mPoints = 
        new HashMap<MyMapPoint, Marker>();
    public static MyMapFragment newInstance(ArrayList<MyMapPoint> points) {
        MyMapFragment fragment = new MyMapFragment();
        Bundle args = new Bundle();
        args.putParcelableArrayList(KEY_POINTS, points);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
        MyMapPoint[] points = mPoints.keySet().toArray(
            new MyMapPoint[mPoints.size()]);
        outState.putParcelableArray(KEY_POINTS, points);
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            Bundle extras = getArguments();
            if ((extras != null) && extras.containsKey(KEY_POINTS)) {
                for (Parcelable pointP : extras.getParcelableArrayList(KEY_POINTS)) {
                    mPoints.put((MyMapPoint) pointP, null);
                }
            }
        } else {
            MyMapPoint[] points = (MyMapPoint[]) savedInstanceState
                .getParcelableArray(KEY_POINTS);
            for (MyMapPoint point : points) {
                mPoints.put(point, null);
            }
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, 
        ViewGroup container, Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.map_fragment, container, false);
        mMapView = (MapView) layout.findViewById(R.id.map);
        return layout;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mMapView.onCreate(savedInstanceState);
        setUpMapIfNeeded();
        addMapPoints();
    }
    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
    }
    @Override
    public void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mMapView.onResume();
    }
    @Override
    public void onDestroy() {
        mMapView.onDestroy();
        super.onDestroy();
    }
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    };
    private void setUpMapIfNeeded() {
        if (mMap == null) {
            mMap = ((MapView) getView().findViewById(R.id.map)).getMap();
            if (mMap != null) {
                setUpMap();
            }
        }
    }
    private void setUpMap() {
        mMap.setOnInfoWindowClickListener(this);
        addMapPoints();
    }
    private void addMapPoints() {
        if (mMap != null) {
            HashMap<MyMapPoint, Marker> toAdd = 
                new HashMap<MyMapPoint, Marker>();
            for (Entry<MyMapPoint, Marker> entry : mPoints.entrySet()) {
                Marker marker = entry.getValue();
                if (marker == null) {
                    MyMapPoint point = entry.getKey();
                    marker = mMap.addMarker(point.getMarkerOptions());
                    toAdd.put(point, marker);
                }
            }
            mPoints.putAll(toAdd);
        }
    }
    @Override
    public void onInfoWindowClick(Marker marker) {
        Fragment fragment = DetailsFragment.newInstance();
        getActivity().getSupportFragmentManager().beginTransaction()
            .replace(R.id.contentPane, fragment)
            .addToBackStack(null).commit();
    }
    public static class MyMapPoint implements Parcelable {
        private static final int CONTENTS_DESCR = 1;
        public int objectId;
        public LatLng latLng;
        public String title;
        public String snippet;
        public MyMapPoint(int oId, LatLng point, 
            String infoTitle, String infoSnippet, String infoImageUrl) {
            objectId = oId;
            latLng = point;
            title = infoTitle;
            snippet = infoSnippet;
        }
        public MyMapPoint(Parcel in) {
            objectId = in.readInt();
            latLng = in.readParcelable(LatLng.class.getClassLoader());
            title = in.readString();
            snippet = in.readString();
        }
        public MarkerOptions getMarkerOptions() {
            return new MarkerOptions().position(latLng)
                .title(title).snippet(snippet);
        }
        @Override
        public int describeContents() {
            return CONTENTS_DESCR;
        }
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(objectId);
            dest.writeParcelable(latLng, 0);
            dest.writeString(title);
            dest.writeString(snippet);
        }
        public static final Parcelable.Creator<MyMapPoint> CREATOR = 
            new Parcelable.Creator<MyMapPoint>() {
            public MyMapPoint createFromParcel(Parcel in) {
                return new MyMapPoint(in);
            }
            public MyMapPoint[] newArray(int size) {
                return new MyMapPoint[size];
            }
        };
    }
}

如果你需要查看任何其他文件,请告诉我。在这里你可以找到一个完整的项目,你只需要把你自己的地图API密钥放在AndroidManifest.xml文件中。

编辑

我设法使示例更加简单,并更新了上面的代码。

以下是我对第一个问题的修复:

当我调用mMap.onCreate(savedInstanceState)时,Map似乎试图对所有捆绑包进行解封,而不仅仅是它自己的信息,如果我使用自定义的Parcelable类,它就会出现问题。对我有效的解决方案是,在我调用Map的onCreate()之前,我一使用它们就从savedInstanceState中删除它们。我用savedInstanceState.remove(MY_KEY)来做。我必须做的另一件事是在Fragment'sonSaveInstanceState(Bundle outState)函数中将我自己的信息添加到outState之前调用mMap.onSaveInstanceState()

以下是我如何处理第二个问题:

我把这个示例项目简化到了最简单的地方。我将原始Markers添加到映射中,如果我用另一个映射替换Fragment,那么在单击"返回"后,我仍然得到"空"映射。所以我做了两件事:

  1. onPause()函数中保存CameraPosition以在onResume()中恢复
  2. onPause()中将mMap设置为null,因此当Fragment返回时,addMapPoints()函数将再次添加Markers(由于我在保存和检查Markers id,所以我不得不稍微更改它(

以下是代码示例:

private CameraPosition cp;

public void onPause() {
    mMapView.onPause();
    super.onPause();
    cp = mMap.getCameraPosition();
    mMap = null;
}

public void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    mMapView.onResume();
    if (cp != null) {
        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));
        cp = null;
    }
}

为了更新onResume()中的相机位置,我不得不手动初始化地图。我在setUpMap():中做过

private void setUpMap() {
    try {
        MapsInitializer.initialize(getActivity());
    } catch (GooglePlayServicesNotAvailableException e) {
    }
    mMap.setOnInfoWindowClickListener(this);
    mMap.setOnMapLongClickListener(this);
    addMapPoints();
}

我意识到这些并不是真正的解决方案,只是覆盖,但这是我目前能做的最好的事情,项目必须继续下去。如果有人找到了更干净的修复方法,我会很感激让我知道它们。

在此处搜索有关onSaveInstanceNullPointerException的任何提示。我尝试过各种变通方法,包括@Izydorr提到的方法,但都没有成功。问题是FragmentPagerAdapter——ViewPager的适配器,它承载了我嵌入MapView s的片段。在将其更改为FragmentStatePagerAdapter后,NPE已经消失。哇!

使用GoogleMap.OnCameraChangeListener和覆盖方法onCameraChange实现片段/活动。您可以保存新的相机位置,onResume使用

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPositionSaved));

相关内容

  • 没有找到相关文章

最新更新