[英]Restoring MapView's state on rotate and on back
背景
我有一個更大的應用程序,我在使用新的Google Maps API時遇到了一些問題。 我嘗試用不同的問題描述它,但由於它看起來太復雜,我決定開始一個新項目,盡可能簡單並嘗試重現問題。 所以這就是。
情況
我正在使用Fragments
並希望將MapView
放入其中。 我不想使用MapFragment
。 我准備的示例項目可能不是很漂亮,但我試圖讓它盡可能簡單,它必須包含原始應用程序中的一些元素(再次簡化)。 我有一個Activity
和我的自定義Fragment
with MapView
以編程方式添加。 Map
包含一些點/ Markers
。 單擊Marker
,顯示InfoWindow
並單擊它會導致在內容中顯示下一個Fragment
(帶有replace()
函數)。
問題
我有兩個問題:
當顯示帶Markers
的Map
,屏幕旋轉導致Class not found when unmarshalling
使用我的自定義MyMapPoint
類Class not found when unmarshalling
錯誤時MyMapPoint
類 - 我不知道為什么以及它意味着什么。
我單擊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];
}
};
}
}
如果您需要查看任何其他文件 - 請告訴我。 在這里,您可以找到一個完整的項目,您只需將自己的Maps API KEY放在AndroidManifest.xml
文件中即可。
編輯
我設法使示例更簡單並更新了上面的代碼。
這是我對第一個問題的解決方法:
看起來Map
正在嘗試解壓縮所有的bundle,而不僅僅是當我調用mMap.onCreate(savedInstanceState)
時它自己的信息,如果我使用我的自定義Parcelable
類它有問題。 對我savedInstanceState
的解決方案是在我使用后立即從savedInstanceState
刪除我的額外內容 - 在我調用Map的onCreate()
。 我用savedInstanceState.remove(MY_KEY)
。 我要做的另一件事是在將自己的信息添加到Fragment's
onSaveInstanceState(Bundle outState)
函數中的outState
之前調用mMap.onSaveInstanceState()
。
以下是我處理第二個問題的方法:
我將示例項目簡化為裸骨。 我正在將原始Markers
添加到地圖中,如果我用另一個地圖替換Fragment
,那么在點擊“返回”之后我仍然會得到“空白”地圖。 所以我做了兩件事:
onPause()
函數中保存CameraPosition
以在onResume()
恢復它 onPause()
mMap
設置為null,因此當Fragment
返回時, addMapPoints()
函數會再次添加Markers
addMapPoints()
因為我保存並檢查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()
中setUpMap()
:
private void setUpMap() {
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
}
mMap.setOnInfoWindowClickListener(this);
mMap.setOnMapLongClickListener(this);
addMapPoints();
}
我意識到那些不是真正的解決方案 - 只是覆蓋,但它是我現在能做的最好的,項目必須繼續。 如果有人發現更清潔的修復,我會很高興讓我知道他們。
來這里搜索有關onSaveInstance
和NullPointerException
的任何提示。 我嘗試過各種各樣的解決方法,包括@Izydorr提到的那個,但沒有運氣。 問題在於FragmentPagerAdapter
- ViewPager
的適配器,它托管了我嵌入MapView
的片段。 在將其更改為FragmentStatePagerAdapter
,NPE已經消失。 呼!
使用GoogleMap.OnCameraChangeListener
實現您的片段/活動並覆蓋方法onCameraChange
並進入您可以保存新攝像機位置,並使用onResume
使用
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPositionSaved));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.