First launch of Activity with Google Maps is very slow

前端 未结 9 1789
礼貌的吻别
礼貌的吻别 2020-12-02 12:37

I want to have SupportMapFragment in one of my Activity. I add this fragment directly to layout xml and this layout set as content view. But when Activity is launched for th

9条回答
  •  误落风尘
    2020-12-02 13:09

    Ok so I just had the same issue and think, after viewing this question, that there is no 'nice' solution.

    My current hack is to delay adding the fragment, giving the Activity a chance to render everything else before adding the map.

    Now, I am embedding the map as a childfragment, so my code looks like this:

        // inside onCreateView
        new Handler().postDelayed(new Runnable() {
    
            @Override
            public void run() {
                if (isAdded()) {
                    FragmentManager fm = getChildFragmentManager();
                    GoogleMapFragment mapFragment = GoogleMapFragment
                            .newInstance();
                    fm.beginTransaction()
                            .replace(R.id.mapContainer, mapFragment).commit();
                }
            }
        }, 1000);
    

    if adding directly to Activity it might look like this:

        // inside onCreate
        new Handler().postDelayed(new Runnable() {
    
            @Override
            public void run() {
                if (!isFinishing()) {
                    FragmentManager fm = getFragmentManager();
                    GoogleMapFragment mapFragment = GoogleMapFragment
                            .newInstance();
                    fm.beginTransaction()
                            .replace(R.id.mapContainer, mapFragment).commit();
                }
            }
        }, 1000);
    

    Nevertheless, a check inside the Runnable is needed to ensure that we are not trying to add the map to some non-existing Activity or Fragment.

    I am not a fan of hardcoded delays like this, so will return if I come up with something better. 1 second should be plenty though and could probably be even less.

提交回复
热议问题