Fragment中的MapView null

时间:2015-04-23 11:28:06

标签: android dictionary fragment

我有这个xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" 
android:background="#f00"
android:gravity="center">

<com.google.android.gms.maps.MapView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map" />

</LinearLayout>

这是我在Fragment中的onCreateView方法中的代码

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.map_activity, container, false);
    mapView = (MapView) view.findViewById(R.id.map);
    mMap = mapView.getMap();

      if (mMap== null)
        {
            Toast.makeText(getActivity().getBaseContext(),"Google Maps not Available",
                    Toast.LENGTH_LONG).show();
        }

       locReader = (LocationReader) new LocationReader(getActivity().getBaseContext(), true);
       this.loc = locReader.getLastKnownLocation(); 
       moveCamMyPosition(loc);

    return view;
}

Fragment加载正常,但nMap为null。 Toast显示“Google Maps not available”。

我找不到错误。

3 个答案:

答案 0 :(得分:3)

尝试使用getMapAsync(OnMapReadyCallback callback)代替getMap()http://developer.android.com/reference/com/google/android/gms/maps/MapView.html

public class myFragment extends Fragment implements OnMapReadyCallback {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /* ... */
        mapView.getMapAsync(this);
        /* ... */
    }

    @Override
    public void onMapReady(GoogleMap map) {
        /* do something with the map */
        mMap = map;
        locReader = (LocationReader) new LocationReader(getActivity().getBaseContext(), true);
        this.loc = locReader.getLastKnownLocation(); 
        moveCamMyPosition(loc);
    }
}

答案 1 :(得分:1)

您是否生成了正确的Google Maps API密钥?

Google地图需要以下权限。

  • ACCESS_NETWORK_STATE - 检查网络状态是否可以下载数据
  • INTERNET - 检查互联网连接状态
  • WRITE_EXTERNAL_STORAGE - 写入外部存储空间,谷歌地图将地图数据存储在外部存储空间中
  • ACCESS_COARSE_LOCATION - 使用WiFi和移动单元数据确定用户的位置
  • ACCESS_FINE_LOCATION - 使用GPS确定用户的位置

OpenGL ES V2 - Google Maps V2需要

答案 2 :(得分:-1)

[STAThread]
private void f() 
{
  ...
}