26

背景

我有一个更大的应用程序,其中我遇到/遇到了新的 Google Maps API 的几个问题。我试图用另一个问题来描述它,但由于它看起来太复杂了,我决定开始一个新项目,尽可能简单并尝试重现问题。所以就在这里。

情况

我正在使用Fragments并想放在MapView里面。我不想使用MapFragment. 我准备的示例项目可能不是很漂亮,但我试图使其尽可能简单,并且它必须包含原始应用程序中的一些元素(再次简化)。我有一个Activity和我的自定义FragmentMapView以编程方式添加。Map包含一些点Markers/ 。单击显示并单击它后,会在内容中显示下一个Marker(带有功能)。InfoWindowFragmentreplace()

问题

我有两个问题:

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

  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>

我的地图片段

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文件中。

编辑

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

4

3 回答 3

31

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

似乎Map正在尝试解包所有捆绑包,而不仅仅是我打电话时它自己的信息mMap.onCreate(savedInstanceState),如果我使用我的自定义Parcelable类,它就会出现问题。对我有用的解决方案是在我使用它们后立即删除我的额外内容savedInstanceState- 在我调用 Map's 之前onCreate()。我用savedInstanceState.remove(MY_KEY). 我必须做的另一件事是mMap.onSaveInstanceState()在将我自己的信息添加到函数之前outState调用Fragment's onSaveInstanceState(Bundle outState)

这是我处理第二个的方式:

我将示例项目简化为最基本的。我正在向地图添加原始Markers地图,如果我将Fragment地图替换为另一张地图,那么在单击“返回”后,我仍然会得到“无效”地图。所以我做了两件事:

  1. 保存功能以将其CameraPosition恢复onPause()onResume()
  2. 设置mMap为null,onPause()所以当Fragment返回时,函数Markers会再次添加addMapPoints()(我不得不稍微更改它,因为我正在保存和检查Markersid)。

以下是代码示例:

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();
}

我意识到这些不是真正的解决方案 - 只是覆盖,但这是我现在能做的最好的,项目必须继续。如果有人找到更清洁的修复程序,我会很感激让我知道它们。

于 2013-05-02T22:45:59.447 回答
1

来这里寻找有关onSaveInstance和的任何提示NullPointerException。我尝试了各种解决方法,包括@Izydorr 提到的解决方法,但都没有运气。问题在于-托管我嵌入s的片段FragmentPagerAdapter的适配器。在将其更改为NPE 之后,它就消失了。哇!ViewPagerMapViewFragmentStatePagerAdapter

于 2016-01-18T22:44:45.903 回答
0

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

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPositionSaved));
于 2015-11-24T09:53:11.190 回答