无法从FragmentManager获取GoogleMap

时间:2014-11-02 18:48:11

标签: android google-maps android-fragments

当我使用GoogleMap map =((SupportMapFragment)manager.findFragmentById(R.id.map))时,为什么会出现空指针异常.getMap()?我必须遗漏一些非常明显的事情:

public class ReviewMap extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_review_map);

        if (savedInstanceState == null) {
            FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().add(R.id.container, new MapFragment()).commit();

            GoogleMap map = ((SupportMapFragment) manager.findFragmentById(R.id.map)).getMap();  // Null pointer exception
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.review_map, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    public static class MapFragment extends Fragment {

        public MapFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_review_map, container, false);
            return rootView;
        }
    }
}

我的布局:

activity_review_map.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="atorch.shortestpaths.ReviewMap"
    tools:ignore="MergeRootFrame" />

fragment_review_map.xml - 这是我尝试使用R.id.map访问的那个:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/map"
  android:name="com.google.android.gms.maps.SupportMapFragment"
  android:layout_width="match_parent"
  android:layout_height="match_parent" />

如果我在第一个代码块中注释掉GoogleMap map =((SupportMapFragment)manager.findFragmentById(R.id.map))。getMap()行,一切都按预期工作(我在ActionBar下看到一个地图);如果我离开该行,我的logcat中会出现Null指针异常,并且应用程序在显示任何地图之前崩溃。

1 个答案:

答案 0 :(得分:1)

在这种情况下,您的Activity布局文件应如下所示:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/home_container"  
    android:layout_width="match_parent" 
    android:layout_height="match_parent">   
    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>
</FrameLayout>

我将地图片段包装在FrameLayout中,以防您想在地图之外添加其他内容到活动中。但是FrameLayout不是必需的。

然后在您的Activity中,您可以在从onCreate()和onResume()调用的函数中设置映射。您可能不需要所有侦听器,我也使用自定义InfoWindow作为标记气球:

private GoogleMap map;

private void setUpMyMap() {
            if (map == null) {
                map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
                // Check if we were successful in obtaining the map
                if (map != null) {
                    try {
                        MapsInitializer.initialize(this);
                    } catch (Exception e) {
                        // That should not happen as we are checking for the map not being null
                    }
                    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    map.getUiSettings().setZoomControlsEnabled(false);
                    map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(40.38944, -98.97639), map.getMinZoomLevel() + 1));
                    map.setOnCameraChangeListener(new OnCameraChangeListener() {
                        @Override
                        public void onCameraChange(CameraPosition position) {
                            // Do something
                        }
                    });
                    map.setOnMapClickListener(new OnMapClickListener() {
                        @Override
                        public void onMapClick(LatLng arg0) {
                            // Do soemthing
                        }
                    });
                    map.setOnMarkerClickListener(new OnMarkerClickListener() {
                        @Override
                        public boolean onMarkerClick(Marker marker) {
                            // A marker was clicked
                            marker.showInfoWindow();
                            map.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()), 800, null);
                            return true;
                        }
                    });
                    map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
                        @Override
                        public void onInfoWindowClick(Marker marker) {
                            // Display the detials
                        }
                    });
                    map.setInfoWindowAdapter(new CustomInfoWindowAdapter(this));
                } else {
                    // This device probably does not support Google Play Services.
                }
            }
        }