无法从Fragment转换为MapFragment

1 android android-fragments android-maps-v2

我遇到了Map Fragment的问题.错误消息是说无法从Fragment转换为MapFragment.我尝试extends FragmentActivity一起改变,GoogleMap map = ((SupportMapFragment) getSupportFragmentManager()但这导致了我onCreateView的代码行的问题.

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class Fragment01 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_01, container, false);

    // Get a handle to the Map Fragment
    GoogleMap map = ((MapFragment) getFragmentManager()
            .findFragmentById(R.id.map)).getMap();

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

}
Run Code Online (Sandbox Code Playgroud)

vip*_*tal 5

更换

getFragmentManager
Run Code Online (Sandbox Code Playgroud)

getSupportFragmentManager
Run Code Online (Sandbox Code Playgroud)

getFragmentManager返回orroids api fragment(可从v11 +获得)类的实例,但是已导入 android.support.v4.app.Fragment.

所以无论是打电话getSupportFragmentManager还是改变运动.

getSupportFragmentManager仅在FragmentActivity类中可用.

所以,你需要首先把这个片段内FragmentActivity(程度FragmentActivityActivity),然后在onActivityCreated片段的方法得到的活性参考,并调用getSupportFragmentManager.例如

myContext.getSupportFragmentManager(); 
Run Code Online (Sandbox Code Playgroud)

for ref.: 如何在片段中访问getSupportFragmentManager()?