我正在尝试动态创建一个SupportMapFragment
并将其放置在一个FrameLayout
容器中。
我的问题是mMapFragment.getMap()
返回null
...
有人能帮忙吗?
CenterMapFragment.java
public class CenterMapFragment extends Fragment {
private SupportMapFragment mMapFragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.center_map_fragment, container, false);
}
@Override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) == ConnectionResult.SUCCESS) {
setUpMapIfNeeded();
}
}
private void setUpMapIfNeeded() {
if (mMapFragment == null) {
mMapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.map, mMapFragment);
fragmentTransaction.commit();
setUpMap();
}
}
private void setUpMap() {
GoogleMap map = mMapFragment.getMap();
// map is null!
}
@Override
public void onResume()
{
super.onResume();
setUpMapIfNeeded();
}
}
center_map_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<Button
android:id="@+id/btn_loc"
android:layout_width="60dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="@drawable/locbtn" />
</RelativeLayout>
CenterMapFragment
扩展了SupportMapFragment
,我该如何将地图设置到FrameLayout
中?我需要更改布局吗? - julCenterMapFragment
实现一个onCreateView()
,首先调用super.onCreateView()
,以获取SupportMapFragment
创建的任何内容。然后它将创建FrameLayout
并将super
创建的View
作为FrameLayout
的子项添加进去。然后从onCreateView()
返回FrameLayout
。这样可以将SupportMapFragment
的内容包装在CenterMapFragment
想要的内容中。或者,让CenterMapFragment
成为普通的Fragment
,使用MapView
而不是SupportMapFragment
。或者,找到更好的时间来使用你当前的代码调用setUpMap()
。 - CommonsWareSupportMapFragment
并从onCreateView()
调用 super 不起作用。仍然出现NullPointerException
! - Muhammad Babar