Viewpager提供已添加的错误片段

时间:2019-03-16 07:39:39

标签: android android-fragments kotlin android-viewpager

我在Viewpager Adapter (FragmentStatePagerAdapter)中说到一个例外

java.lang.IllegalStateException: Fragment already added: CodeAnswerFragment{8c1a4d1 #0 id=0x7f0902fb}

我已经使用basefragment来设置所有Fragments。这适用于某些片段,但不适用于所有片段。尽管片段中的代码相同

 inner class AnswerFragmentAdapter(private val answerFragmentList : List<BAF>,
                            fm : FragmentManager) : FragmentStatePagerAdapter(fm) {
    override fun getCount(): Int {
        return answerFragmentList.size
    }

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

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        // Ignored : Avoid reloading answer fragment
    }
}

这是我设置ViewPager的地方

val answers : List<Answer> = state.loadingExtras as List<Answer>
                if(answers.isNotEmpty()) {
                    val answerFragmentList: ArrayList<BAF> = arrayListOf()
                    var bundle : Bundle
                    var answerFragment: BAF
                    for (answer in answers) {
                        bundle = Bundle()
                        answerFragment = getNewAnswerFragmentInstance()
                        bundle.putSerializable(BaseAnswerFragment.KEY_ANSWER, answer)
                        answerFragment.arguments = bundle
                        answerFragmentList.add(answerFragment)
                    }
                    setUpViewPager(answerFragmentList)

protected open fun setUpViewPager(answerFragmentList : List<BAF>) {

    activity?.supportFragmentManager?.let {
        answerFragmentAdapter = AnswerFragmentAdapter(answerFragmentList, it)
    }

    baseAnswerSectionDataBinding.layoutViewpager.viewpagerAnswer.adapter =
            answerFragmentAdapter
}

0 个答案:

没有答案