慕运维0750787
2021-07-21 14:41
private fun switchFragment(selectIndex: Int) { if (tab1Fragment == null) { tab1Fragment = StudyFragment() // 添加参数 addBundleToFragment(tab1Fragment!!, "tab1") } if (tab2Fragment == null) { tab2Fragment = StudyFragment() // 添加参数 addBundleToFragment(tab2Fragment!!, "tab2") } if (tab3Fragment == null) { tab3Fragment = StudyFragment() // 添加参数 addBundleToFragment(tab3Fragment!!, "tab3") } //获取fragment对象 val fragment: Fragment? = when (selectIndex) { 0 -> { tab1Fragment } 1 -> { tab2Fragment } 2 -> { tab3Fragment } else -> { throw IllegalStateException("${selectIndex}下标不符合预期") } } ?: return //如果fragment为空,则返回 // 切换fragment显示 if (fragment != null) { if (!fragment.isAdded) { fragmentTransaction.add(R.id.fragment_container, fragment)//添加fragment } fragmentTransaction.show(fragment)//显示fragment } // 隐藏之前显示的shownFragment,以多个Fragemnt重叠 if (shownFragment != null) { fragmentTransaction.hide(shownFragment!!) } shownFragment = fragment//设置当前显示的为fragment fragmentTransaction.commitAllowingStateLoss()//提交业务 }
报错指向这一行:
fragmentTransaction.commitAllowingStateLoss()//提交业务
整个文件只有这一个提交业务 ,为什么说已经called
val fragmentTransaction = supportFragmentManager.beginTransaction() 这个必须定义为局部变量,若定义为全局变量,只能提交一次。
2021Android从零入门到实战(Kotlin版)
18954 学习 · 74 问题
相似问题