片段尚未附加

时间:2019-10-28 16:42:38

标签: android kotlin fragment

在阅读有关此异常的帖子后,我不明白我需要做什么来纠正此错误。此外,我什至无法重现...有时在某些设备上会发生这种情况,但我不知道如何...

我的日志:

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

HostFragment类:

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

MainActivity类:

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

ViewPager适配器:

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()
    }
}

我总是使用新的片段实例从addFragment调用MainActivity(我不会重用旧片段的实例。)

尚未附加哪个片段?我的HostFragment或我要添加的新片段。

1 个答案:

答案 0 :(得分:1)

您的应用程序崩溃是因为FragmentStatePagerAdapter的实现不正确。

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

您不得在Fragment*PagerAdapter中保留片段列表,因为系统会重新创建片段,并且您将在该列表中调用的一个您将实际上不会添加到FragmentManager。

您可以做的就是将FragmentStatePagerAdapter切换为FragmentPagerAdapter,然后可以应用App crash after activity has been killed in backgroundHow to get elements of fragments created by ViewPager in MainActivity?

要重现崩溃,请参考Singleton object becomes null after app is resumed