Nath5
Nath5

Reputation: 1655

Extend MapFragment Android

I have an activity that hosts two fragments. One fragment provides some info to the user in various fields. The other fragment should show a Map.

For the fragment hosting the map I need to be able to add custom logic for displaying markers and several other things that I would like to reuse in other places in the app. What is the best way to create a map without defining the fragment in xml like:

<fragment
class="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

Thanks, Nathan

Edit:

I am now using nested fragments, not sure if that is the best way to handle this? My mapfragment is now:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />
</LinearLayout>

and the Fragments code is:

public class ViewCurrentMapFragment extends Fragment implements View.OnClickListener {
    public static final String TAG = "MAP_FRAGMENT";

    private GoogleMap map;


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

    private void getCurrentMarkers() {
        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment smf = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map));

        map = smf.getMap();

    }

    @Override
    public void onClick(View v) {
    }


    @Override
    public void onResume() {
        super.onResume();
        getCurrentMarkers();
    }

}

The problem I am having now is that smf.getMap() is returning null. Any ideas?

Edit2:

Got it to work by changing:

com.google.android.gms.maps.MapFragment

to

com.google.android.gms.maps.SupportMapFragment

Upvotes: 4

Views: 3568

Answers (1)

MaciejG&#243;rski
MaciejG&#243;rski

Reputation: 22232

Maybe:

<fragment
    class="com.mycompany.MyCustomFragmentExtendingMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

or nest fragments like here: http://code.google.com/p/gmaps-api-issues/issues/detail?id=5064#c1

Upvotes: 1

Related Questions