Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

The answer Matt suggests works, but it cause the map to be recreated and redrawn, which isn’t always desirable.
After lots of trial and error, I found a solution that works for me:

private static View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);
    }
    try {
        view = inflater.inflate(R.layout.map, container, false);
    } catch (InflateException e) {
        /* map is already there, just return view as it is */
    }
    return view;
}

For good measure, here’s “map.xml” (R.layout.map) with R.id.mapFragment (android:id=”@+id/mapFragment”):

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

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>

I hope this helps, but I can’t guarantee that it doesn’t have any adverse effects.

Edit: There were some adverse effects, such as when exiting the application and starting it again. Since the application isn’t necessarily completely shut down (but just put to sleep in the background), the previous code i submitted would fail upon restarting the application. I’ve updated the code to something that works for me, both going in & out of the map and exiting and restarting the application, I’m not too happy with the try-catch bit, but it seem to work well enough. When looking at the stack trace it occurred to me that I could just check if the map fragment is in the FragmentManager, no need for the try-catch block, code updated.

More edits: Turns out you need that try-catch after all. Just checking for the map fragment turned out not to work so well after all. Blergh.

Leave a Comment