記錄一次關(guān)于底部導(dǎo)航切換的crash:Fragment already added驱还。
觸發(fā):打開app,快速點(diǎn)擊底部按鈕切換fragment的時候 大概率會出現(xiàn)這個問題精堕。
排查過程:出現(xiàn)這個crash的時候孵淘,一開始想到的便是在 supportFragmentManager.beginTransaction().add前判斷是否已經(jīng)添加過fragment.isAdded,查看代碼發(fā)現(xiàn)這個邏輯已經(jīng)存在...就有點(diǎn)意思了歹篓!然后通過日志發(fā)現(xiàn)瘫证,確實(shí)是add了多次揉阎,經(jīng)過查閱知道commit執(zhí)行的是一個延時的異步操作,
Schedules a commit of this transaction. The commit does not happen immediately;
it will be scheduled as work on the main thread to be done the next time that thread is ready.
這樣就可能導(dǎo)致快速點(diǎn)擊的時候上次可能還沒commit完成背捌,所以解決思路便是讓它立即執(zhí)行毙籽。
image.png
解決辦法:1.
supportFragmentManager.executePendingTransactions()
立即執(zhí)行 。這個是我自己采用的方式毡庆;2.這個問題是在一個老項目中發(fā)現(xiàn)的坑赡,然后就順手看了一下自己近期新搭建的項目,是采用一打開app便把所有fragment先add進(jìn)去么抗,這樣的話也不會出現(xiàn)這個crash毅否,性能上硬考慮比較,那肯定還是1好一些蝇刀!