2

一个片段,我有以下2布局文件:findFragmentById返回不存在

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <fragment android:id="@+id/list_fragment" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight="1" 
     class="MyListFragment"/> 

</LinearLayout> 

(w900dp)

<fragment android:id="@+id/list_fragment" 
    android:layout_width="0dp" 
    android:layout_height="match_parent" 
    android:layout_weight=".3" 
    class="MyListFragment"/> 

<fragment android:id="@+id/content_fragment" 
    android:layout_width="0dp" 
    android:layout_height="match_parent" 
    android:layout_weight=".7" 
    class="MyContentFragment"/> 

然后在我的活动我有:

public class ReportActivity extends ActionBarActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.report); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

     // Get the content fragment 
     MyContentFragment contentFragment = (MyContentFragment) getSupportFragmentManager().findFragmentById(R.id.content_fragment); 
     if (contentFragment != null) { 
      // sometimes I get a handle to this fragment when I should not 
      contentFragment.updateContent(//some content); 
     } 
    } 

我的问题是这样的。当我以横向模式启动应用程序时,宽度足以显示这两个片段。当我旋转到纵向时,它不再足够宽,没有内容片段的布局文件被加载。但是,当我调用片段管理器来获取该片段时,它会找到它。然后当我调用更新内容失败,因为该片段内的UI组件不再存在。

为什么getFragmentById返回确实存在的片段,但在设备旋转后不再存在?

回答

0

我怀疑问题是您的getFragmentById()调用正在返回原始片段 - 在横向启动应用程序时创建的片段。这可能是因为在轮换期间重新创建活动时,该片段被分离(但未被销毁),然后将其实例添加到活动中。你的getFragmentById()可以工作,但它返回的(原始)片段已被分离,所以它没有膨胀的布局 - 所以更新内容调用失败。

如果没有更多的活动代码,很难解决问题。您应确保在创建活动期间创建并附加片段时,首先检查片段管理器中是否已存在片段。

.... 
Fragment frag = fragmentManager.findFragById(id); 
if (frag == null) { 
    frag = MyFrag.newInstance(); 
} 
fragmentManager.replace(...,frag,...)... 

我实际上会使用findFragmentByTag(),因为我发现跟踪哪个片段是那么容易。更换碎片时,请确保设置唯一标签。

+1

谢谢。但是,我不编程创建片段,Android为我做它,因为它们在我的布局文件中。 I.E.我没有发布更多活动代码的原因是因为没有更多。当您在xml布局文件中使用片段标签时,android会创建/销毁片段。 – lostintranslation 2015-04-02 21:57:51

+0

你可能想尝试手动处理它,因为框架似乎没有做得很好。 – athingunique 2015-04-02 21:59:22

相关问题