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

相關問題