活动旋转时片段重叠 [英] Fragment overlaps on activity rotation

查看:51
本文介绍了活动旋转时片段重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此感到非常困惑.我有一个带有列表导航的 actionbar .我单击列表以一个接一个地打开2个 fragment ,并在同一活动中显示.我基本上是使用这种方法替换它们:

I'm getting really confused about this. I have an actionbar with list navigation. I click on the list to open 2 fragment one after another and display in the same activity. I'm basically replacing them using this method:

public void openFragment(AprilAppsFragment createdFragment){        
    if (createdFragment.getClass().isInstance(getDisplayedFragment()))
        return;

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

    transaction.replace( R.id.main_fragment, createdFragment, "displayed fragment"); 
    transaction.addToBackStack(null);
    transaction.commit();  
}

我打开片段 A ,然后打开片段 B ,然后旋转屏幕.正在重新创建片段 A ,导致我的应用崩溃

I open fragment A, then I open fragment B, then I rotate the screen. Fragment A is being recreated crashing my app

为什么会这样,因为我正在使用replace?我该如何避免重新创建不再显示的片段,而又不会对它们施压呢?

Whys is that, since I'm using replace? How do I avoid recreating fragments that no longer being shown, without losing possibility of back-pressing to them?

推荐答案

您的问题是您没有保存碎片的状态,并且由于您没有添加

Your problem is that you are not saving state for your fragments, and since you haven't added

android:configChanges="orientation|screenSize"

您的第一个片段再次被调用,由于您没有保存状态,因此您的应用程序崩溃了.这样很好,您可以在清单中的Activity声明中在上面添加以下行:

your first fragment is called again, and since you have no saved state your app crashes. So its good that you add the line above in you Activity declaration in the manifest like:

<activity android:name=".yourActivity" android:configChanges="orientation|screenSize"

并覆盖onSaveInstanceState并保存两个片段的状态.并在您的onCreate中执行以下检查:

and Override the onSaveInstanceState and save states for both your fragments. And in your onCreate just do this check:

if(savedInstanceState != null){
fragmentA = (FragmentA) fragmentManager.getFragment(savedInstanceState, stringValueA);
fragmentB = (FragmentB) fragmentManager.getFragment(savedInstanceState, stringValueB);
}

然后检查您的任何片段是否不为null,然后创建其实例并将其设置为fragmentTransaction.relplace.或在您的openFragment方法中执行此操作.

And then check if any of your fragment is not null than create its instance and set that to fragmentTransaction.relplace. Or do this in your for openFragment method.

干杯

这篇关于活动旋转时片段重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆