Skip to content Skip to sidebar Skip to footer

Getting A Reference To A GoogleMap In A Fragment Using Support Library V4

I'm trying to add Google Maps to a fragment using the v4 support lib, but I have some trouble using getMap() to reference it. I'm adding the fragment like so (following the example

Solution 1:

In your FragmentTransaction in MainActivity you should add an instance of SupportMapFragment instead of MapFragmentClass.

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if (findViewById(R.id.fragment_container) != null) {

            SupportMapFragment mapFragmentClass= new SupportMapFragment ();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, mapFragmentClass).commit();
            getSupportFragmentManager().executePendingTransactions();
            GoogleMap map = mapFragmentClass.getMap();
            // do what you need to do with the map
        }
    }
}

The way you were creating SupportMapFragment was just creating a new Fragment instance but since you didn't add it using a FragmentTransaction none of the lifecycle methods of the Fragment were being called.


Post a Comment for "Getting A Reference To A GoogleMap In A Fragment Using Support Library V4"