Fragment: Yes or Not

2014, square在其技術(shù)博客上發(fā)表了Advocating Against Android Fragments,闡述了使用fragment可能會遇到的問題。

  1. lifecycle過于復(fù)雜
  2. hard to debug, FragmentManagerImpl的代碼過于復(fù)雜。
  3. Fragment transactions 是異步的(post到UI隊列的尾端),可能導(dǎo)致程序處于未知的狀態(tài)
  4. 創(chuàng)建匿名內(nèi)部Fragment時,如果activity要恢復(fù)這個fragment時,會因為找不到無參構(gòu)造函數(shù)而報錯。
    比如
DialogFragment dialogFragment = new DialogFragment() {
  @Override public Dialog onCreateDialog(Bundle savedInstanceState) { ... }
};
dialogFragment.show(fragmentManager, tag);

會出現(xiàn)以下錯誤

android.support.v4.app.Fragment$InstantiationException:
    Unable to instantiate fragment com.squareup.MyActivity$1:
    make sure class name exists, is public, and has an empty
    constructor that is public

所以Square提倡使用custom view來取代Fragment。

不過Fragments也有其自身的好處:

  1. 能夠保存view的狀態(tài),如果用custom view,需要開發(fā)者自己保存狀態(tài),增加了復(fù)雜度
  2. 對backstack的支持,custom view如果要支持backstack,需要使用第三方庫,比如FlowSimpleStack。

一種使用Fragment的pattern是One-Activity-Multiple-Fragments architecture。

現(xiàn)在Fragment的bug大多已經(jīng)fix了,通過使用MVP,將business logic移到Presenter中,可以減少Fragment的錯誤。所以還是大膽用Fragment吧

Fragment 仍然存在的bug(已用最新的support-v7:26.1.0測試來源):

  1. Nested Fragment在父Fragment的離開動畫時會消失

  2. Nested Fragment setRetainInstance is inherited(已經(jīng)修復(fù))

  3. Nested Fragment onActivityResult is broken(已經(jīng)修復(fù))

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容