Я попытался выполнить 2 транзакции фрагмента в onCreate()
:
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()
}
, однако получил исключение NullPointerException для переменной options
.Но когда я разделяю 2-ю транзакцию на метод 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()
}
Может кто-нибудь объяснить, почему это так?