Fragment with Map crashes app when back button is pressed or when orientation changes

本秂侑毒 提交于 2019-12-04 18:26:37

I seem to have solved both the back button and orientation change problem.

The trick here is to not use onDestroyView(), but to change the way the fragments are handled. instead of ft.attach(mFragment) and ft.detach(mFragment), I changed them to ft.show(mFragment) and ft.hide(mFragment).

As for the orientation change causing the app to crash, I believe (do correct me if I am wrong) that as long as you do not have an alternative landscape layout, you can add android:configChanges="orientation|screenSize" to the manifest for this activity, like this:

<activity 
        android:theme="@style/AppTheme" 
        android:name="MyFragmentActivity" 
        android:label="@string/fragmentActivity" 
        android:configChanges="orientation|screenSize">
    </activity>

The GoogleMap needs a little bit of time to load, so it could return null if you want use it. Try moving this code in the onActivityCreated() method of your MapFragment

map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
Marker amksc = map.addMarker(new MarkerOptions().position(mapLatLng).title("Map"));

map.moveCamera(CameraUpdateFactory.newLatLngZoom(mapLatLng, 18)); 

That used to work for me. Be sure to check out the Fragment Lifecycle

it was work for me.. try it the below code write in the onDestory() method

@Override
    public void onDestroy() { 
if (fragment != null
                        && getFragmentManager().findFragmentById(
                                fragment.getId()) != null) {

                    getFragmentManager().beginTransaction().remove(fragment)
                            .commit();
                    fragment = null;
                }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!