Fragment has not been attached yet

非 Y 不嫁゛ 提交于 2019-12-20 04:29:05

问题


After reading posts on this exception, I can't understand what I need to do to correct this error. Besides, I can't even reproduce it... This happens sometimes on some devices but I don't understand how...

my logs :

Fatal Exception: java.lang.IllegalStateException
Fragment a has not been attached yet my.app.HostFragment.addFragment

HostFragment class :

fun addFragment(fragment: Fragment) {
        childFragmentManager.beginTransaction()
          .add(R.id.fragment_root_container, fragment)
          .addToBackStack(null)
          .commit()
}

MainActivity class :

fun openNewChampionFragment() {
        val hostFragment = pagerAdapter.getItem(viewpager.currentItem) as HostFragment
        hostFragment.addFragment(ChampionFragment.newInstance())
}

ViewPager Adapter :

class ViewPagerAdapter(manager: FragmentManager) : FragmentStatePagerAdapter(manager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

    private var fragments: MutableList<Fragment> = mutableListOf()

    fun addFragments(fragments: List<Fragment>) {
        this.fragments = fragments.toMutableList()
    }

    override fun getItem(position: Int): Fragment {
        return fragments[position]
    }

    override fun getCount(): Int {
        return fragments.size
    }

    fun clearStack(index: Int){
        (fragments[index] as HostFragment).clearAllStack()
    }
}

I always call addFragment from my MainActivity with a new fragment instance (I don't reuse the instance of the old fragments.)

Which fragment has not been attached ? My HostFragment or the new one that i'm trying to add.


回答1:


Your app crashes because the implementation of FragmentStatePagerAdapter is incorrect.

// private var fragments: MutableList<Fragment> = mutableListOf() // <-- remove this line entirely

You mustn't keep a list of fragments in your Fragment*PagerAdapter, because the system recreates the Fragments, and the one you'll be invoking in that list will never actually be added to the FragmentManager.

Something you can do is switch FragmentStatePagerAdapter to FragmentPagerAdapter, then you can apply App crash after activity has been killed in background and How to get elements of fragments created by ViewPager in MainActivity? .

To reproduce your crash, refer to Singleton object becomes null after app is resumed .



来源:https://stackoverflow.com/questions/58594982/fragment-has-not-been-attached-yet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!