2014, square在其技術(shù)博客上發(fā)表了Advocating Against Android Fragments,闡述了使用fragment可能會遇到的問題。
- lifecycle過于復(fù)雜
- hard to debug, FragmentManagerImpl的代碼過于復(fù)雜。
- Fragment transactions 是異步的(post到UI隊列的尾端),可能導(dǎo)致程序處于未知的狀態(tài)
- 創(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也有其自身的好處:
- 能夠保存view的狀態(tài),如果用custom view,需要開發(fā)者自己保存狀態(tài),增加了復(fù)雜度
- 對backstack的支持,custom view如果要支持backstack,需要使用第三方庫,比如Flow,SimpleStack。
一種使用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測試來源):
Nested Fragment在父Fragment的離開動畫時會消失
Nested Fragment setRetainInstance is inherited(已經(jīng)修復(fù))
Nested Fragment onActivityResult is broken(已經(jīng)修復(fù))