[我在android studio中为不同的地图样式创建了一个选项菜单,但是当我尝试加载它时崩溃

问题描述 投票:0回答:1

因此,我希望我的地图显示不同的地图样式,并为此选择菜单。我仍在学习,但我似乎不知道为什么当我运行该应用程序并选择任何这些选项时,我的应用程序会崩溃。它与正常的应用程序一起工作,然后立即关闭,但此后它们都不起作用。

我的代码:

public class MapsActivityRaw extends AppCompatActivity
        implements OnMapReadyCallback {

    private static final String TAG = MapsActivityRaw.class.getSimpleName();
    public GoogleMap map;


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

        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.map_options, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Change the map type based on the user's selection.
        switch (item.getItemId()) {
            case R.id.normal_map:
                map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                return true;
            case R.id.hybrid_map:
                map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                return true;
            case R.id.satellite_map:
                map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                return true;
            case R.id.terrain_map:
                map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

java android android-studio google-maps-android-api-2
1个回答
0
投票

崩溃的一个可能原因是您的map可能尚未在onMapReady()触发的mapFragment.getMapAsync(this);函数中初始化

菜单没有问题。

为了安全起见,在if (mMap != null)内部添加onOptionsItemSelected()检查。

  @Override
  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Change the map type based on the user's selection.
    if (mMap != null) {
      switch (item.getItemId()) {
        case R.id.normal_map:
          // ...
        case R.id.hybrid_map:
          // ...
        default:
          return super.onOptionsItemSelected(item);
      }
    }
    return super.onOptionsItemSelected(item);
  }
© www.soinside.com 2019 - 2024. All rights reserved.