Fragment $ Companion无法在BottomNavigationView侦听器上强制转换为androidx.fragment.app.Fragment

时间:2019-10-28 08:16:29

标签: android android-fragments kotlin androidx fragmentmanager

我的底部导航视图应该与选项卡一起使用,但是以某种方式我无法投射

  

片段为片段

再用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的用法,但是此解决方案对解决我的问题没有帮助。

1 个答案:

答案 0 :(得分:1)

更改

val fragment = MissionListFragment

val fragment = MissionListFragment()

使用fragment = MissionListFragment链接companion object的{​​{1}}