我的底部导航视图应该与选项卡一起使用,但是以某种方式我无法投射
片段为片段
再用AndroidX
每次单击菜单项时都有崩溃
java.lang.ClassCastException: com.spacexmonitor.MissionListFragment$Companion cannot be cast to androidx.fragment.app.Fragment
at com.spacexmonitor.MainActivity$onCreate$menuOnNavigationItemSelectedListener$1.onNavigationItemSelected(MainActivity.kt:28)
有我的活动:
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
if (savedInstanceState == null) {
fragmentTransaction.replace(R.id.container, MissionListFragment())
fragmentTransaction.commit()
}
val menuOnNavigationItemSelectedListener =
bottomNavigationBar.setOnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.launchesMenuItem -> {
val fragment = MissionListFragment
fragmentTransaction.replace(R.id.container, fragment as Fragment)
.commit()
return@setOnNavigationItemSelectedListener true
}
R.id.chartsMenuItem -> {
val fragment = MissionChartFragment
fragmentTransaction.replace(R.id.container, fragment as Fragment)
.commit()
return@setOnNavigationItemSelectedListener true
}
}
false
}
}
}
我的空片段:
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class MissionChartFragment : Fragment() {
companion object {
private val MISSION_CHART = "mission chart"
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_mission_chart, container, false)
}
}
很多答案是将app.Fragment
更改为v4.Fragment
的用法,但是此解决方案对解决我的问题没有帮助。
答案 0 :(得分:1)
更改
val fragment = MissionListFragment
到
val fragment = MissionListFragment()
使用fragment = MissionListFragment
链接companion object
的{{1}}