Maps V2 with viewPager

user2558461 picture user2558461 · Aug 22, 2013 · Viewed 7.1k times · Source

I'm currently developing for Android 4.3.
Background:
I'm using pageViewer to scroll between three different fragments. My second fragment (tab 2) has XML with SupportMapFragment and other content. as shown below :
My problem http://imageupload.co.uk/files/vrhg1e06x977rkm1vhmd.jpg
My Attempt:
While searching the web I noticed that for SupportMapFragment I need FragmentActivity which doesn't apply for FragmentPagerAdapter. I need the user to have the ability to control the map as well as control the rest of the content in the fragment.
My Question:
How can I use the SupportMapFragment with the viewPager while having more content in the Fragment?

More about my code: in the getItem inside FragmentPagerAdapter I'm returning Singleton Fragments (each Fragment has a class) therefore I couldn't find any solution over the Internet since my class can't extend SupportMapFragment because it has more data.

Answer

MaciejGórski picture MaciejGórski · Aug 22, 2013

Since Android 4.2 (also in the support library for pre-Jelly) you can use nested fragments.

You can see how to create such fragment is:

public class MyFragment extends Fragment {

    private SupportMapFragment fragment;
    private GoogleMap map;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_with_map, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        FragmentManager fm = getChildFragmentManager();
        fragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
        if (fragment == null) {
            fragment = SupportMapFragment.newInstance();
            fm.beginTransaction().replace(R.id.map_container, fragment).commit();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (map == null) {
            map = fragment.getMap();
            map.addMarker(new MarkerOptions().position(new LatLng(0, 0)));
        }
    }
}

Above code copied from here.

Impoatant note: your custom Fragments's layout cannot contain <fragment> tag.