简体   繁体   中英

Use google map support fragment in fragment

I am currently doing an application with my main activity as a NavigationDrawer. So, to navigate through my application any other "activity" is a fragment and, in one of thoses fragment I need to put a GoogleMap support fragment. The point is that when, in my fragment, I do getFragmentManager.findFragmentById(R.id.map); it returns null.

Here is what my code looks like.

//fragment_home.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">

    <fragment
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
//My HomeFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_home, container, false);

    FragmentManager manager = getFragmentManager();

    SupportMapFragment mapFragment = (SupportMapFragment)manager.findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    return view;
}

Do anyone have an idea on how to fix this? I already looked for solutions on this website and many others but I can't figure how to get the fragment stored in the xml layout of my "parent" fragment.

Thanks for your help, Cordially, Matthieu Meunier

If you are to use a SupportMapFragment inside a Fragment you can't use getFragmentManager method. Instead use the following method.

SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM