如何正确初始化地图?

时间:2014-06-03 06:42:40

标签: android android-fragments google-maps-api-2 android-maps-v2

如何在片段中初始化地图?我现在正在获得nullpointerexception。我有一个片段, Fragment01 ,它只显示地图和布局 Fragment_01.xml ,它只包含地图。

清单          

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="19" />

<permission
android:name="se.sebastianliljegren.nellienovafoto.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>

<uses-permission android:name="se.sebastianliljegren.nellienovafoto.permission.MAPS_RECEIVE"/>
<library
    android:name="com.google.android.maps"
    />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- The following two permissions are not required to use
 Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

    <meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="############################"/>

    <activity
        android:name="se.sebastianliljegren.nellienovafoto.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</manifest>

MainActivity     公共类MainActivity扩展了FragmentActivity {

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

    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    StartFragment startfragment = new StartFragment();

    transaction.add(R.id.fragment_placeholder, startfragment);
    transaction.commit();
}

public void onSelectFragment(View view){

    Fragment newFragment;

    if (view == findViewById(R.id.btnomforetaget)) {
        newFragment = new StartFragment();
    } else if (view == findViewById(R.id.btnhittahit)) {
        newFragment = new Fragment01();
    } else if (view == findViewById(R.id.btnhemsida)) {
        newFragment = new Fragment02();
    } else {
        newFragment = new StartFragment();
    }

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_placeholder, newFragment);
    transaction.addToBackStack(null);
    transaction.commit();

}

}

Fragment01

public class Fragment01 extends Fragment {
MapView mapView;
GoogleMap map;


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

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 view;
}

@Override
public void onDestroyView()
{
  super.onDestroyView();
   Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));  
  FragmentTransaction ft =     getActivity().getSupportFragmentManager().beginTransaction();
  ft.remove(fragment);
  ft.commit();

}

}

Fragment_01.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:id="@+id/fragment02">
<fragment android:id="@+id/map"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:name="com.google.android.gms.maps.MapFragment"/>
</LinearLayout>

4 个答案:

答案 0 :(得分:2)

你的 android:minSdkVersion =“11”所以你应该改变这个

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

并且也改变了这个

 map= ((MapFragment) getFragmentManager().findFragmentById(
            R.id.map)).getMap();

 map= ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
            R.id.map)).getMap();

还可以使用以下内容更改onDestroyView()

 @Override
    public void onDestroyView()
    {
        try{
          SupportMapFragment fragment = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map));
          FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
          ft.remove(fragment);
          ft.commit();
        }catch(Exception e){
        }
      super.onDestroyView();  
  }

还会在Fragmnt01

中的下导入
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import com.google.android.gms.maps.SupportMapFragment;

答案 1 :(得分:1)

您忘记在onCreateView()内初始化地图:

 map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
        .getMap();

当您使用minSDKVersion = 11时,您需要使用SupportMapFragment,同时更改相同的XML内部代码。

答案 2 :(得分:1)

在你的onCreateView()方法中,你必须初始化地图,如:

if (map== null) {
        map= ((SupportMapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

并在你的xml中:

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

答案 3 :(得分:0)

U会使用类似下面的内容:

公共静态类MapsFragment扩展了Fragment {

    private SupportMapFragment suppfrag;
    LatLng sydney = new LatLng(-33.867, 151.206);
    private GoogleMap map;

    public static final String ARG_SECTION_NUMBER = "section_number";

    public MapsFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

            return inflater.inflate(R.layout.fragment_map, container, false);
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        FragmentManager fm = getChildFragmentManager();
        suppfrag = (SupportMapFragment) fm.findFragmentById(R.id.map);
        if (suppfrag == null) {
            suppfrag = SupportMapFragment.newInstance();
            fm.beginTransaction().replace(R.id.map, suppfrag).commit();

            Marker location = map.addMarker(new MarkerOptions().position(CENTRU)
                    .title("Centru"));
                location.setIcon(BitmapDescriptorFactory
                                    .defaultMarker(BitmapDescriptorFactory.HUE_BLUE));

                // Move the camera instantly to Bottlecapp with a zoom of 15.
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(CENTRU, 15));

                // Zoom in, animating the camera.
                map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
                getActivity().getSupportFragmentManager().popBackStack();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        if (map == null) {
            map = suppfrag.getMap();
            map.addMarker(new MarkerOptions().position(new LatLng(0, 0)));
        }
    }
}

如果您使用片段,则xml文件类似于下面的文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

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

</RelativeLayout>