0

我正在使用藍牙連接創建應用程序。連接在一個簡單對象(HandleConnection)內處理。當連接建立時,我的應用程序進入「遠程」模式,這意味着我將使用「HandleConnection」對象的另一個(RemoteFragment)替換我的主片段。配置更改後重置片段

直到一切都在我的「的onCreate」(我的活動內)結束的很順利,因爲我設置了RemoteFragment的的handleConnection屬性:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main_layout); 


    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); 
    if (savedInstanceState == null) { 
     retainedFragment = new RetainedFragment(); 
     getFragmentManager().beginTransaction().add(retainedFragment, RetainedFragment.class.toString()).commit(); 
     handleConnection = new HandleConnection(this, handler); 
     retainedFragment.setHandleConnection(handleConnection); 

    } else { 

     remoteFragment = (RemoteFragment) getFragmentManager().findFragmentByTag(RemoteFragment.class.toString()); 
     retainedFragment = (RetainedFragment) getFragmentManager().findFragmentByTag(RetainedFragment.class.toString()); 

     if (remoteFragment == null) 
      remoteFragment = new RemoteFragment(); 

     handleConnection = retainedFragment.getHandleConnection(); 
     remoteFragment.setHandleConnection(handleConnection); 
    } 

    fragmentTransaction.commit(); 

} 

一切正常,除非我變成橫向模式的罰款。 然後(在調試模式下播放後),看起來我的調用器被調用後重新創建了RemoteFragment,這顯然意味着我的handleConnection屬性爲null。 它爲什麼這樣做?我會理解,如果我沒有重用前一個片段(那麼我會有兩個不同的片段在另一個之上),但在這種情況下,它是沒有意義的。 我通過調用onCreateView中的回調函數來獲得HandleConnection對象,但是爲什麼當我之前調用setter時該屬性爲null?

謝謝!

回答

0

因此很明顯,我的問題是,我沒有使用正確的我的RemoteFragment的實例,這意味着我的當前引用(在我的活動中)對於我的對象有正確的非空值,但顯示的片段不是這一個(它是舊的被重新創建並因此具有空值爲handleConnection)。

0

片段的生命週期直接受宿主活動生命週期的影響。當活動被破壞時,所有的碎片也會被破壞。在佈局更改期間,活動將被銷燬並重新創建。

在這種情況下,在輪換之後,onCreate()方法中的else條件將執行,因此您將收到的行爲。查看文檔以獲得全面瞭解。

http://developer.android.com/guide/components/fragments.html

+0

是的,但因爲我調用''''remoteFragment.setHandleConnection(handleConnection);''''進入onCreateView時,remoteFragment不應該有空指針? – pLesur

+0

在你的其他情況下,當你調用'handleConnection = retainedFragment.getHandleConnection();'這個句柄連接null?我想這是空的。在將其設置爲'remoteFragment'之前,您應該有一個可空性檢查。 – Sabeeh

+0

不,handleConnection不爲空。我一直在使用Android doc中提到的RetainedFragment模式:[link](http://developer.android.com/guide/topics/resources/runtime-changes.html) – pLesur

0

您需要添加到您的活動登記AndroidManifes.xml類似的東西:<activity android:configChanges="orientation|screenSize"/>

閱讀this文章