【发布时间】:2015-07-04 08:55:21
【问题描述】:
我有一个无法扩展到片段活动的主要活动。首先,我直接在其中显示我的谷歌地图,一切正常。但是后来我必须使用这些片段,所以我已经将我的所有其他活动(MainActivity 除外)转换为片段,并且能够成功调用它们并替换它们。但是问题来了。当我需要将我的谷歌地图放入一个单独的片段并在我的主要活动启动时调用它时..它会加载地图但看起来它没有正确实例化地图
包含地图的 MyMapFragment 的 xml 如下所示:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.abdulsalamali.letscoffee.MyMapFragment">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment
android:id="@+id/mapView"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/rl_address" />
</RelativeLayout>
</FrameLayout>
在此地图创建的活动中,我正在尝试像这样初始化地图
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
createMapView();
// and doing some stuff here such as camera animation
}
private void createMapView() {
/**
* Catch the null pointer exception that
* may be thrown when initialising the map
*/
try {
if (null == googleMap) {
MapFragment mapFragment = new MapFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
// transaction.add(R.id.rl_map_container, mapFragment).commit();
googleMap= mapFragment.getMap();
googleMap = ((SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.mapView)).getMap();
googleMap.setBuildingsEnabled(true);
googleMap.setMyLocationEnabled(true);
/**
* If the map is still null after attempted initialisation,
* show an error to the user
*/
if (null == googleMap) {
Toast.makeText(getActivity(),
"Error creating map", Toast.LENGTH_SHORT).show();
}
}
} catch (NullPointerException exception) {
Log.e("mapApp", exception.toString());
}
}
所以它不是动画它只是显示地图,没有设置当前位置,没有为 myLocationEnabled 启用按钮。实际上它返回 googleMap 实例为 null。
我已经阅读了很多东西并得到了嵌套片段的提示,但无法理解如何使其工作,我搜索了许多教程,他们正在使用我不想使用的片段活动。所以请帮助我,我想我的问题很清楚。
【问题讨论】:
-
stackoverflow.com/questions/18206615/… -- 我想这会解决你的问题
-
@koutuk 在接受的答案中有很多我无法理解的东西,你能试着详细说明一下吗?
-
哪一部分不清楚....
标签: android google-maps android-fragments android-nested-fragment