分类器没有伴随对象

时间:2018-08-13 22:45:56

标签: android-studio kotlin fragment companion-object

我想在我的应用程序中使用BottomNavigationView,而我却遇到了kotlin的问题(Java从未遇到过),我看到此消息: 分类器“ listFragment”没有伴随对象,因此必须在此处初始化

这是我的代码:

private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.listNav -> {
//the problem is here in listFragment word below
            setFragment(listFragment)
            return@OnNavigationItemSelectedListener true
        }
        R.id.accountNav -> {
//the problem is here also in accountFragment word below
            setFragment(accountFragment)
            return@OnNavigationItemSelectedListener true
        }
false 
}
private fun setFragment(fragment: Fragment) {
    supportFragmentManager.beginTransaction().replace(R.id.mainFrame , fragment).commit()
}

我们将不胜感激:)

2 个答案:

答案 0 :(得分:1)

我以这种方式对其进行了编辑,并且有效:

private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.listNav -> {
            val mFragment = cartFragment.newInstance()
            openFragment(mFragment)
            return@OnNavigationItemSelectedListener true
        }
        R.id.cartNav -> {
            val mFragment = cartFragment.newInstance()
            openFragment(mFragment)
            return@OnNavigationItemSelectedListener true
        }
        R.id.supportNav -> {
            val mFragment = supportFragment.newInstance()
            openFragment(mFragment)
            return@OnNavigationItemSelectedListener true
        }
        R.id.accountNav -> {
            val mFragment = accountFragment.newInstance()
            openFragment(mFragment)
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}
private fun openFragment(fragment: Fragment) {
    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.mainFrame, fragment)
    transaction.addToBackStack(null)
    transaction.commit()
}

片段如下:

class listFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
        inflater.inflate(R.layout.fragment_list, container, false)

companion object {
    fun newInstance(): listFragment = listFragment()
}

}

答案 1 :(得分:0)

如果有人(像我一样)在when块中产生的标题错误中挣扎, 与sealed对象进行比较时,请不要忘记is关键字,如下所示:

when (someSealedClass) {
        is SomeSealedClass.Foo -> ...
//      ^^ don't forget this
      }