How to put Google Maps V2 on a Fragment using ViewPager

前端 未结 13 2137
攒了一身酷
攒了一身酷 2020-11-22 04:56

I am trying to do a tab layout same in Play Store. I got to display the tab layout using a fragments and viewpager from androidhive. However, I can\'t implement google maps

13条回答
  •  轮回少年
    2020-11-22 05:41

    According to https://developer.android.com/about/versions/android-4.2.html#NestedFragments, you can use nested fragments to achieve this by calling getChildFragmentManager() if you still want to use the Google Maps fragment instead of the view inside your own fragment:

    SupportMapFragment mapFragment = new SupportMapFragment();
    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.add(R.id.content, mapFragment).commit();
    

    where "content" is the root layout in your fragment (preferably a FrameLayout). The advantage of using a map fragment is that then the map lifecycle is managed automatically by the system.

    Although the documentation says "You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically. ", I have somehow successfully done this and it worked fine. Here is my code:
    In the fragment's onCreateView() method:

    View view = inflater.inflate(R.layout.layout_maps, container, false);
    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(...);
    

    In the layout:

    
    

    Hope it helps!

提交回复
热议问题