【问题标题】:classifier does not have a companion object分类器没有伴随对象
【发布时间】:2019-01-20 17:27:27
【问题描述】:

我想在我的应用程序中使用 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()
}

感谢任何帮助:)

【问题讨论】:

  • 我认为您没有正确初始化 listFragment,这就是您收到此错误的原因。能否请您添加此活动的完整代码和 LIstFragment 的代码?
  • 我找到了解决方案,请查看答案@MehulKanzariya

标签: android-studio kotlin fragment companion-object


【解决方案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()
}

}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多