以编程方式添加时检索 SupportMapFragment 的 GoogleMap 成员时出错



在膨胀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" />

此代码:

mGoogleMap = supportMap.getMap() ;

应该在创建之后调用。试试 onResume(),像这样。

@Override
protected void onResume() {
    super.onResume();
    // here it should work
    mGoogleMap = supportMap.getMap(); 
    // In case Google Play services has since become available.
    setUpMapIfNeeded();
}

最新更新