Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

android - SupportMapFragment - cannot cast from Fragment to MapFragment

Trying to put together a little MapFragment in an activity I'm building, but am having some trouble getting it all to work. I know that the Maps api and Play services are both installed correctly, as I did the test tutorial and everything worked fine.

Following the documentation here, I'm running into the following problem: In my setUpMapIfNeeded method, I can either use getFragmentManager() or getSupportFragmentManager(). When I use the getFragmentManager(), Eclipse is cool with it but when I run, I get a NoSuchMethodError saying that the method is undefined. When I opt for getSupportFragmentManager(), Eclipse doesn't like it and gives me the error "Cannot cast from Fragment to MapFragment". So what's the deal? Any suggestions?

private void setUpMapIfNeeded() {
    //Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        mMap = ((MapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        if (mMap != null) {
            //do things to the map
            mMap.addMarker(new MarkerOptions().position(LOCATION).title(EXTRA_URL));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LOCATION,15));
            mMap.getUiSettings().setZoomControlsEnabled(false);
        }
    }
}

Let me know if there's any other code I can provide and I'll be happy to post it quickly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I can either use getFragmentManager() or getSupportFragmentManager().

There should be no debate here. If getSupportFragmentManager() is available to you, then you are using the Android Support package's backport of fragments, and this is the method that you must use.

When I opt for getSupportFragmentManager(), Eclipse doesn't like it and gives me the error "Cannot cast from Fragment to MapFragment".

That is because you should not be using MapFragment. You are using the Android Support package's backport of fragments, and therefore you must use SupportMapFragment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...