0

在有一些解析问题使 XML 膨胀后,我决定做一个程序化的解决方法。地图已正确添加到场景中,但我在将其缓存为类成员以供以后使用时遇到问题。这是带有爆炸点的代码片段。

活动:

public class MoogliActivity extends FragmentActivity {

public void onCreate(final Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  this.setContentView(R.layout.main);
  final SupportMapFragment supportMap = SupportMapFragment.newInstance();
  final FragmentTransaction fragmentTransaction = this.getSupportFragmentManager()
            .beginTransaction();
 fragmentTransaction.add(R.id.maplayout, supportMap);
 fragmentTransaction.commit();
 mGoogleMap = supportMap.getMap(); // mGoogleMap = null after this
 // mGoogleMap.setMyLocationEnabled(true); Obviously NullPointerException
}

}

主要的.xml

<RelativeLayout
    android:id="@+id/maplayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignBottom="@+id/tracking"
    android:layout_below="@id/header" />
4

1 回答 1

0

This code:

mGoogleMap = supportMap.getMap();

Should be called after onCreate. Try onResume(), like this.

@Override
protected void onResume() {
    super.onResume();

    // here it should work
    mGoogleMap = supportMap.getMap(); 

    // In case Google Play services has since become available.
    setUpMapIfNeeded();
}
于 2013-01-19T18:59:33.933 回答