Using Google Maps inside a Fragment in Android

后端 未结 2 1257
迷失自我
迷失自我 2021-01-16 10:36

I am trying to load Google Maps inside fragment ,and I keep getting the same error regardless of what solution I am trying to implement. I have already gone though all of t

相关标签:
2条回答
  • 2021-01-16 10:45

    You can do this as a normal fragment.

    public void replaceFragment(Fragment fragment, String fragmentTag){
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.container, fragment);
                fragmentTransaction.addToBackStack(fragmentTag);
                fragmentTransaction.commit();
            }
    
    private void initMap(){
            MapFragment mapFragment = MapFragment.newInstance();
            replaceFragment(mapFragment, fragmentTag);
            mapFragment.getMapAsync(this);
        }
    
    0 讨论(0)
  • 2021-01-16 10:55

    line 66 of your MapsFragment, replace:

    // Try to obtain the map from the SupportMapFragment.
    mMap = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map))
        .getMap();
    

    by:

    // Try to obtain the map from the SupportMapFragment.
    mMap = ((SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map))
        .getMap();
    

    Because your map fragment is a fragment in a fragment, and not managed by the top level FragmentManager.

    Also, I am not sure but you may want to setup your Map asynchronously:

        ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMapAsync(
        new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                setUpMap();
            }
        });
    
    0 讨论(0)
提交回复
热议问题