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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…