问题描述
在阅读有关此异常的帖子后,我不明白我需要做些什么来纠正此错误.此外,我什至无法重现...有时在某些设备上会发生这种情况,但我不知道如何...
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...
我的日志:
Fatal Exception: java.lang.IllegalStateException
Fragment a has not been attached yet my.app.HostFragment.addFragment
HostFragment类:
HostFragment class :
fun addFragment(fragment: Fragment) {
childFragmentManager.beginTransaction()
.add(R.id.fragment_root_container, fragment)
.addToBackStack(null)
.commit()
}
MainActivity类:
MainActivity class :
fun openNewChampionFragment() {
val hostFragment = pagerAdapter.getItem(viewpager.currentItem) as HostFragment
hostFragment.addFragment(ChampionFragment.newInstance())
}
ViewPager适配器:
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()
}
}
我总是用新的片段实例从MainActivity
调用addFragment
(我不重用旧片段的实例.)
I always call addFragment
from my MainActivity
with a new fragment instance (I don't reuse the instance of the old fragments.)
尚未附加哪个片段?我的HostFragment或我要添加的新片段.
Which fragment has not been attached ? My HostFragment or the new one that i'm trying to add.
推荐答案
您的应用程序崩溃是因为FragmentStatePagerAdapter
的实现不正确.
Your app crashes because the implementation of FragmentStatePagerAdapter
is incorrect.
// private var fragments: MutableList<Fragment> = mutableListOf() // <-- remove this line entirely
您不必在Fragment*PagerAdapter
中保留片段列表,因为系统会重新创建片段,并且您要在该列表中调用的一个 永远不会真正添加到FragmentManager.
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.
您可以执行的操作是将FragmentStatePagerAdapter
切换为FragmentPagerAdapter
,然后您可以应用和.
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? .
要重现崩溃,请参考 Singleton对象在应用恢复后变为空.
这篇关于片段尚未附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!