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

前端 未结 23 1648
-上瘾入骨i
-上瘾入骨i 2020-11-22 00:25

I have an application with three tabs.

Each tab has its own layout .xml file. The main.xml has its own map fragment. It\'s the one that shows up when the application

23条回答
  •  攒了一身酷
    2020-11-22 01:02

    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"):

    
    
    
        
    
    

    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.

提交回复
热议问题