在onCreate()中不可能进行2个片段事务

时间:2019-04-13 12:44:15

标签: android android-fragments kotlin oncreate fragmenttransaction

我尝试在onCreate()中执行2个片段事务:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    bottomNav_main.setOnNavigationItemSelectedListener(this)

    val firstFragment = OpeningFragment()
    firstFragment.arguments = intent.extras
    val transaction = supportFragmentManager.beginTransaction()
    transaction.add(R.id.fragment_layout, firstFragment, "add_activitymain")
    transaction.add(R.id.fragment_layout, OptionsFragment(), "add_options")
    transaction.add(R.id.fragment_layout, LeaderboardsFragment(), "add_leaderboards")
    transaction.commit()

    val transaction2 = supportFragmentManager.beginTransaction()
    val options: Fragment = supportFragmentManager.findFragmentByTag("add_options")!!
    val leaderboards: Fragment = supportFragmentManager.findFragmentByTag("add_leaderboards")!!
    transaction2.hide(options)
    transaction2.hide(leaderboards)
    transaction2.commit()
}

但是在options变量上收到了NullPointerException。但是,当我将第二笔交易分成onStart()方法时,它可以正常工作:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    bottomNav_main.setOnNavigationItemSelectedListener(this)

    val firstFragment = OpeningFragment()
    firstFragment.arguments = intent.extras
    val transaction = supportFragmentManager.beginTransaction()
    transaction.add(R.id.fragment_layout, firstFragment, "add_activitymain")
    transaction.add(R.id.fragment_layout, OptionsFragment(), "add_options")
    transaction.add(R.id.fragment_layout, LeaderboardsFragment(), "add_leaderboards")
    transaction.commit()
}

override fun onStart() {
    super.onStart()
    val transaction2 = supportFragmentManager.beginTransaction()
    val options: Fragment = supportFragmentManager.findFragmentByTag("add_options")!!
    val leaderboards: Fragment = supportFragmentManager.findFragmentByTag("add_leaderboards")!!
    transaction2.hide(options)
    transaction2.hide(leaderboards)
    transaction2.commit()
}

有人可以解释为什么吗?

2 个答案:

答案 0 :(得分:0)

主要是因为提交交易不会立即发生。它需要几秒钟,并且可以异步工作。尝试使用commitNow()使其即时且同步。

答案 1 :(得分:0)

  

在onCreate()中无法进行片段过渡

尝试在 onViewCreated()

中进行操作
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    create()
}