我在我的应用程序中使用抽屉菜单。我从菜单中选择一个选项并打开片段,然后从该片段调用一个Activity.Since这里工作正常但是当我按下后退按钮(OnbackPress)时,应用程序崩溃了。 吼叫是错误的。 "无法启动活动... ClassCastException ...无法强制转换为Home_Tab"
这是MainActivity代码。
if (savedInstanceState == null) {
homefragment = Home_tab()
fragmentTransaction = fragmentManager!!.beginTransaction()
fragmentTransaction!!.replace(R.id.frame, homefragment)
fragmentTransaction!!.addToBackStack(null)
fragmentTransaction!!.commit()
} else {
homefragment = supportFragmentManager.fragments[0] as Home_tab //Crash at this line
}
调用backPress的代码。
override fun onBackPressed() {
super.onBackPressed()
finish()
}
答案 0 :(得分:0)
//Add a check like this before casting.
//It is a smart cast and you can directly use the result.
Fragment fragmentZero = supportFragmentManager.fragments[0]
if (fragmentZero is Home_tab) {
//Casting is done, you can directly use fragment here
homefragment = fragmentZero
}
答案 1 :(得分:0)
根据您的代码,您可以将片段添加到fragmentmanager(常规代码),但尝试从supportfragmentmanager返回。这是两个不同的类,你的片段只能扩展一个
答案 2 :(得分:0)
你是mixin片段管理器和支持片段管理器,我会选择suppport,因为这是正确的方法。要使用findFragmentById
if (savedInstanceState == null) {
homefragment = Home_tab()
supportFragmentManager?.let{
fragmentTransaction = it.beginTransaction()
fragmentTransaction.replace(R.id.frame, homefragment)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
}
} else {
homefragment = supportFragmentManager.findFragmentById(R.id.frame) as Home_tab
}