I am developing an Android Activity which has two Fragments. The Activity has two possible layouts, one in Portait, and another one in Landscape.
I have created the Fragments working well, but I'm having troubles when I change the orientation of the Phone/tablet.
One of this Fragment is a ListFragment, with an AsyncTask to load the list data from the web. With this Fragment I don't have problems, because I can create it again. (Although it takes a while loading).
The other Fragment has a Google Map V2 fragment inside:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/mapInicio"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
I create the fragments from the onCreate
method of the FragmentActivity
:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio);
Fragment listFragment = new ListaEstaciones();
FragmentTransaction transList = getSupportFragmentManager()
.beginTransaction();
transList.add(R.id.listaestaciones_f_container, listFragment);
transList.commit();
Fragment mapFragment = new MapaGoogleV2();
FragmentTransaction transMap = getSupportFragmentManager()
.beginTransaction();
transMap.add(R.id.mapa_f_container, mapFragment);
transMap.commit();
}
In the onConfigurationChanged
method, I have this code. As in onCreate
, I create the Fragments, and I change the view because now we are on Landscape/Portrait:
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_inicio);
Fragment listFragment = new ListaEstaciones();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.listaestaciones_f_container, listFragment);
transaction.commit();
Fragment mapFragment = new MapaGoogleV2();
FragmentTransaction transMap = getSupportFragmentManager()
.beginTransaction();
transMap.add(R.id.mapa_f_container, mapFragment);
transMap.commit();
}
When I create in this method the ListFragment works great, but is not working with the MapFragment. The application chrash in the onCreateView
method of the Fragment with a Map. I think I can't inflate again this fragment:
04-16 18:20:32.795: E/AndroidRuntime(15543): android.view.InflateException: Binary XML file line #6: Error inflating class fragment
My questions:
Is there a way to avoid the recreation of the fragments when changing the layout?
How can I do this?
Thanks!