无法从Fragment转换为MapFragment

时间:2014-05-29 13:18:49

标签: android android-fragments android-maps-v2

我遇到地图碎片问题。错误消息是无法从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));
}

}

2 个答案:

答案 0 :(得分:5)

替换

getFragmentManager

getSupportFragmentManager

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

因此,请致电getSupportFragmentManager或更改输入。

getSupportFragmentManager仅在FragmentActivity类中可用。

因此,您需要先将此片段放入FragmentActivity(范围FragmentActivity而不是Activity),然后在onActivityCreated片段方法中获取活动参考并调用{ {1}}。 e.g。

getSupportFragmentManager

for ref。: How can I access getSupportFragmentManager() in a fragment?

答案 1 :(得分:4)

尝试这些代码行,它们可能会对您有所帮助:

android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
supportMapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.map);
Google_Map = supportMapFragment.getMap();