android MapView in Fragment

后端 未结 5 1353
小蘑菇
小蘑菇 2020-11-30 02:49

I want to have MapView inside my Fragment

This is my FragmentLayout xml file



        
5条回答
  •  隐瞒了意图╮
    2020-11-30 03:15

    Adding to M D's answer:

    From documentation:

    A GoogleMap must be acquired using getMapAsync(OnMapReadyCallback). The MapView automatically initializes the maps system and the view.

    According to this, the more correct way to initialize GoogleMap is using getMapAsync.

    Note that your class has to implement OnMapReadyCallback

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_map_page, container, false);
    
        mMapView = (MapView) v.findViewById(R.id.map_view);
        mMapView.onCreate(savedInstanceState);
        mMapView.getMapAsync(this); //this is important
    
        return v;
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
        mGoogleMap.addMarker(new MarkerOptions().position(/*some location*/));
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(/*some location*/, 10));
    }
    
    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }
    
    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }
    
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
    

提交回复
热议问题