开发者

GoogleMap Fragment issues

开发者 https://www.devze.com 2023-04-13 07:47 出处:网络
I\'m converting an application I\'ve written and part of it is a GoogleMap component which I\'m trying to put in to a fragment and I\'m having issues.

I'm converting an application I've written and part of it is a GoogleMap component which I'm trying to put in to a fragment and I'm having issues.

I first had a look at android-support-v4-googlemaps and wasn't happy that every FragmentActivity would implement Maps, but having followed these instructions on how to make a MapFragmentActivity I was having problems as now the map would show but on rotating I'd get the "You are only allowed to have a single MapView in a MapActivity error" - followin开发者_C百科g this answer of registering the MapView in code, in the fragment, I got the error that I could only register the MapView in a MapActivity.

So I've now implemented android-support-v4-googlemaps and I'm still getting the error on rotation.

I've come to a dead end, and I'm getting a bit frustrated - does anyone know how to fix this?


I had the same problem with the android-support-v4-googlemaps library. The solution was quite simple after reading carefully how fragments work. Basically, the framework saves the state of fragments on rotation. So, what you need to do is to only instantiate your fragments if there is no saved state (i.e. at the first run of your activity).

Here is an example code that worked for me:

public class MyMapFragmentActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        //... init views, do stuff ...

        // Only instantiate fragments at first run
        if (savedInstancestate == null) {
            // Add map & list fragments
            FragmentManager fm = getSupportFragmentManager();
            MapFragment mapFragment = new MapFragment();
            AnotherFragment another = new AnotherFragment();
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(R.id.fragment_map, mapFragment, "fragment_map");
            ft.add(R.id.fragment_another, anotherFragment, "fragment_another");
            ft.commit();
        }

        //... do more stuff ...
    }

}

In this case I didn't even override the onSavedInstanceState(), as I didn't have anything to save. Keep in mind that this solutions is using the FragmentMapActivity library hack.

I hope this helps.


Google released the Map API Version 2. This gives you a MapFragment and a SupportMapFragment. This should solve the problems you had before.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号