我希望能够通过用户按下操作栏按钮在列表片段和地图片段之间切换。目前我可以很好地在它们之间进行交换,但是在尝试从片段中获取实际的 GoogleMap 对象时遇到了空指针。当我尝试移动相机时,它不会移动,因为 GoogleMap 对象为空并跳过了该代码。我不确定这是否是由于我从未真正从 xml 创建 Fragment 而是仅使用代码?我的代码如下:
public class MapFragment extends SherlockMapFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = super.onCreateView(inflater, container, savedInstanceState);
return root;
}
}
@Override
public void swapFragments() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
if (listFragment.isVisible()) {
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
transaction.replace(R.id.root, mapFragment);
} else {
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
transaction.replace(R.id.root, listFragment);
}
transaction.commit();
}
@Override
public void setupMapFragment() {
mapFragment = new MapFragment();
mMap = mapFragment.getMap();
if (mMap != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(BuzzbabaApplication.latitude,
BuzzbabaApplication.longitude), 14));
}
}