在我的应用程序中,我以编程方式使用谷歌地图,但是当我调用getMap()时,它返回null。即使我已经尝试过onActivityCreated(),但它仍然返回null。谁来帮帮我……这是我的代码,
public void callMap() {
try {
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(mActivity);
if (status == ConnectionResult.SUCCESS) {
Log.d("sreedhu", "Google Play Service Available");
gmo = (new GoogleMapOptions()).zoomControlsEnabled(true)
.rotateGesturesEnabled(true);
mapFragment = SupportMapFragment.newInstance(gmo);
map=mapFragment.getMap();
manager=getFragmentManager();
FragmentTransaction fragmentTransaction = manager
.beginTransaction();
fragmentTransaction.add(R.id.mapFragmentHole, mapFragment);
fragmentTransaction.commit();
manager.executePendingTransactions();
mapFragment=getMap();
} else if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
ErrorDialogFragment.newInstance(status).show(
getFragmentManager(), "errorDialog");
} else {
Toast.makeText(mActivity, "Google Map v2 not available",
Toast.LENGTH_LONG).show();
mActivity.popFragments();
}
} catch (Exception e) {
Log.d("sreedhu", "play" + e.toString());
}
}
executePendingTransactions似乎不像您期望的那样工作。
当MapFragment从代码中创建时,你不会从它得到GoogleMap,直到它的onCreateView被调用。
你需要调用map=mapFragment.getMap();
和它之后的所有代码在onStart或onResume
最后,我得到了这个问题的解决方案…
我在onCreateView上包含了下面的片段,它解决了我的问题,
SupportMapFragment mFragment;
mFragment = new SupportMapFragment() {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if ((map = mFragment.getMap()) != null) {
setUpMap();
}
}
};
一旦地图准备好了,SuppotMapFragment的onActivityCreated将在那里被调用,你可以设置你的地图