android - 在 fragment 内初始化 map

标签 android google-maps android-fragments nullpointerexception supportmapfragment

我在初始化 map 时遇到问题。 map fragment 被膨胀到主要 Activity 的 FrameLayout 中。我在 setUpMapIfNeeded() 方法中不断收到空指针异常。

activity_main.xml

    <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"> 

`         
        <include layout="@layout/toolbar"/>

        <FrameLayout
                android:id="@+id/frameLayout"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"></FrameLayout>
    </LinearLayout>



    <android.support.design.widget.NavigationView
            android:id="@+id/navigation_view"
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
            android:layout_gravity="start"
            app:headerLayout="@layout/header"
            app:menu="@menu/drawer"
            />

</android.support.v4.widget.DrawerLayout>

map fragment .xml

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


    <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/map"
            tools:context=".MapFragment"
            android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

主 Activity .java

switch (menuItem.getItemId()) {
                case R.id.shop:

                    MapFragment mapFragment = new MapFragment();
                    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction.replace(R.id.frameLayout,mapFragment);
                    fragmentTransaction.commit();

                    break;
                case R.id.list:
                    ListFragment listFragment = new ListFragment();
                    android.support.v4.app.FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
                    fragmentTransaction1.replace(R.id.frameLayout,listFragment);
                    fragmentTransaction1.commit();

                    break;
                case R.id.points:
                    Toast.makeText(getApplicationContext(),"Global card selected",Toast.LENGTH_SHORT).show();
                    break;
            }
            return true;
        }
    });

map fragment .java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.map_fragment,container,false);

    //Check if GPS is enabled
    locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        Toast.makeText(getContext(),"GPS enabled",Toast.LENGTH_SHORT).show();
    }else {
        showGPSDisabledAlertToUser();
    }

    setUpMapIfNeeded();
    return view;
}

 private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        //I get a null pointer exception at this point, no map it gotten
        mMap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

最佳答案

看看我的 mapTab 仓库 here .它显示了如何在 fragment 中初始化谷歌地图。

示例代码:

public class MapTabFragment extends Fragment {

    private SupportMapFragment mMapView;

    public static MapTabFragment newInstance(String param1, String param2) {
        MapTabFragment fragment = new MapTabFragment();
        return fragment;
    }

    MapView mapView;
    GoogleMap map;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_map, container, false);
        // Gets the MapView from the XML layout and creates it

        MapsInitializer.initialize(getActivity());


        switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity())) {
            case ConnectionResult.SUCCESS:
                Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
                mapView = (MapView) v.findViewById(R.id.map);
                mapView.onCreate(savedInstanceState);
                // Gets to GoogleMap from the MapView and does initialization stuff
                if (mapView != null) {
                    map = mapView.getMap();
                    map.getUiSettings().setMyLocationButtonEnabled(false);
                    map.setMyLocationEnabled(true);
                    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
                    map.animateCamera(cameraUpdate);
                }
                break;
            case ConnectionResult.SERVICE_MISSING:
                Toast.makeText(getActivity(), "SERVICE MISSING", Toast.LENGTH_SHORT).show();
                break;
            case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
                Toast.makeText(getActivity(), "UPDATE REQUIRED", Toast.LENGTH_SHORT).show();
                break;
            default:
                Toast.makeText(getActivity(), GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()), Toast.LENGTH_SHORT).show();
        }

        // Updates the location and zoom of the MapView

        LatLng sydney = new LatLng(-33.867, 151.206);

        map.setMyLocationEnabled(true);
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

        map.addMarker(new MarkerOptions()
                .title("Sydney")
                .snippet("The most populous city in Australia.")
                .position(sydney));

        return v;
    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
}

为此的 XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

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

</RelativeLayout>

关于android - 在 fragment 内初始化 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33409265/

相关文章:

android - fragment 中的 inflaterException

android - 从 Activity 中的后退按钮开始 fragment

android - 在 SQLite where 子句中进行数学计算

google-maps - 使用 jquery 调整 Google Maps api v3 DIV 的大小 - 图 block 无法正确刷新

javascript - 如何比较地理围栏中的纬度和经度值?

google-maps - 谷歌地图静态与动态商业和建筑物 View

javascript - 更改 Geocoder.geocode() 返回结果的语言

android - 以编程方式将自定义 View 添加到 fragment 布局

android - 自定义日期选择器对话框android

android - 在不同密度下使用 dp 和 sp 时遇到问题