android – SupportMapFragment的getMap()返回null

前端之家收集整理的这篇文章主要介绍了android – SupportMapFragment的getMap()返回null前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图动态创建一个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>

解决方法

FragmentTransaction上的commit()不会立即执行其操作.当你调用setUpMap()时,onCreateView()将不会在SupportMapFragment上被调用,因此在那里
将不会是地图.

一种方法是不使用嵌套片段,而是选择使CenterMapFragment扩展SupportMapFragment,在这种情况下,getMap()应该在onCreateView()之后的任何时间工作(例如onActivityCreated()).

猜你在找的Android相关文章