我正在开发一个包含两个片段的Android Activity。活动有两种可能的布局,一种在Portait中,另一种在Landscape中。
我创建了Fragments,但是当我改变手机/平板电脑的方向时,我遇到了麻烦。
其中一个片段是 ListFragment ,其中有一个AsyncTask用于从Web加载列表数据。有了这个片段,我没有问题,因为我可以再次创建它。 (虽然需要一段时间加载)。
其他片段里面有一个Google Map V2片段:
<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>
我使用onCreate
的{{1}}方法创建片段:
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();
}
方法中,我有这段代码。与在onConfigurationChanged
中一样,我创建了片段,并且我更改了视图,因为现在我们正在使用Landscape / Portrait:
onCreate
当我在这个方法中创建时,ListFragment工作得很好,但是没有使用MapFragment。应用程序在片段的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();
}
方法中使用地图进行chrash。我想我不能再次膨胀这个片段:
04-16 18:20:32.795:E / AndroidRuntime(15543):android.view.InflateException:二进制XML文件行#6:错误膨胀类片段
我的问题:
有没有办法在更改布局时避免重新创建片段?
我该怎么做?
谢谢!
答案 0 :(得分:2)
如果不使用onConfigurationChanged
方法,则无法避免销毁活动,但此解决方案有时难以处理。
在网上研究之后,我发现very interesting article正在讨论如何处理片段的重新创建,但是这个解决方案对我的Map Fragment不起作用。
我的最终解决方案是让Android自动更改布局,从清单中删除android:configChanges=”orientation”
。
另外,我无法使用封闭Google Map V2的Map Fragment。我直接使用了Google Map V2片段。
要保留片段的实例,您只需要输入指令setRetainInstance(true)
:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio);
Fragment listFragment = new ListaEstaciones();
listFragment.setRetainInstance(true);
FragmentTransaction transList = getSupportFragmentManager()
.beginTransaction();
transList.add(R.id.listaestaciones_f_container, listFragment);
transList.commit();
}
感谢您的帮助。
答案 1 :(得分:0)
如果您需要的是纵向和横向的不同布局,则可以更轻松地执行此操作。创建一个文件夹layout-land并将布局XML放在那里,以便为要在横向中指定不同布局的任何片段/活动。 Android会根据方向来处理要使用的布局。有关详情,请访问developer.android.com Check out this page。