我试图在片段中动态加载SupportMapFragment,这是我的onCreateView()方法:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.frag_map_layout, null);
shopDtos=ShopListFragment.shopDtos;
fragment =SupportMapFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.map_content, fragment);
ft.commit();
map = fragment.getMap();
mapMarker = map.addMarker(new MarkerOptions().position(new LatLng(0, 0))
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.maps_pin)));
return contentView;
}
不幸的是,我将GoogleMap地图设为null
。
关于如何动态创建mapfragment的任何建议?
答案 0 :(得分:13)
map需要一些时间来加载,因此您需要在处理程序中运行代码 - >
Handler handler = new Handler();
handler.postDelayed(new Runnable()
@Override
public void run() {
GoogleMap googleMap = SupportMapFragment.newInstance(new GoogleMapOptions().zOrderOnTop(true)).getMap();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.map_content, fragment);
ft.commit();
if(googleMap != null) {
googleMap.addMarker(new MarkerOptions().position(result)).setVisible(true);
// Move the camera instantly to location with a zoom of 15.
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(result, 15));
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.getUiSettings().setCompassEnabled(false);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
handler.removeCallbacksAndMessages(null);
}
else {
handler.postDelayed(this, 500);
}
}, 500);
答案 1 :(得分:3)
尝试使用以下代码。它对我有用。
public class MapFragment extends SupportMapFragment {
GoogleMap mapView;
private Context context;
@Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
@Override
public View onCreateView(LayoutInflater mInflater, ViewGroup arg1,
Bundle arg2) {
View view = super.onCreateView(mInflater, arg1, arg2);
return view;
}
@Override
public void onInflate(Activity arg0, AttributeSet arg1, Bundle arg2) {
super.onInflate(arg0, arg1, arg2);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
context = getActivity();
mapView = getMap();
}
}
答案 2 :(得分:2)
围绕同一主题有一堆重复的问题......我似乎无法弄清楚如何将其标记为重复,然后将一个答案放在其上......
以下是另一个链接:Android SupportMapFragment.getMap() returns null
也有可能的答案:
检查布局xml文件。我注意到我没有引用: android:name =“com.google.android.gms.maps.SupportMapFragment”但是 相反:android:name =“com.google.android.gms.maps.MapFragment”
名称应为: 机器人:名称= “com.google.android.gms.maps.SupportMapFragment”
答案 3 :(得分:1)
在我购买的设备尚未安装/更新Google Play服务的情况下,我遇到过这种情况。当然,提到的其他注释也会考虑这个。
答案 4 :(得分:1)
此问题的最新解决方案是改为使用getMapAsync (OnMapReadyCallback callback)。
答案 5 :(得分:0)
getChildFragmentManager().findFragmentById(R.id.map)
在Fragment中尝试getChildFragmentManager()。