kotlin.TypeCastException:null 无法转换为非 null 类型 android.support.v7.widget.Toolbar

Des*_*d A 5 android fragment kotlin

我是新来Android的。我的问题可能是什么情况?我正在尝试将我的片段呈现给MainActivity. 任何建议都会有所帮助。谢谢

主要活动课...

class NavigationActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_schedule)

        val toolbar = findViewById(R.id.toolbar) as Toolbar
        setSupportActionBar(toolbar) // setup toolbar
        toolbar.setNavigationIcon(R.drawable.ic_map)

        val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
        val toggle = ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
        drawer.addDrawerListener(toggle) // navigation drawer
        toggle.syncState()

        val navigationView = findViewById(R.id.nav_view) as NavigationView
        navigationView.setNavigationItemSelectedListener(this) //setup navigation view

}
Run Code Online (Sandbox Code Playgroud)

我的片段类..

 class fragment_schedule : Fragment() {
 override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
   // Inflate the layout for this fragment
   return inflater!!.inflate(R.layout.fragment_schedule, container, false)
}
Run Code Online (Sandbox Code Playgroud)

Кла*_*арц 0

您的布局显然没有带有 id 的工具栏组件R.id.toolbar,这就是为什么findViewById(...)返回null无法转换为Toolbar.

空安全性在Kotlin. 它可以帮助您在开发的早期阶段揭示大部分 NPE。在官方网站上阅读有关空安全的更多信息Kotlin

如果工具栏组件的存在是必要的,那么永远不要使val toolbar变量可为空。

在这种情况下,您当前的代码是正确的,请勿更改它。相反,请纠正您的布局/错误的工具栏 ID 问题。

var toolbar: Toolbar? = null定义类型可为 null 的变量Toolbar,如果您的活动布局中没有工具栏组件,则不会引发异常,但如果您希望真正拥有此组件,稍后您将得到其他异常,甚至程序的不可预测的行为会让您感到惊讶或应用程序用户

另一方面,您应该在使用可为空变量时进行空安全检查

在这种情况下,您的代码应该稍微改变一下。重要部分:

val toolbar = findViewById(R.id.toolbar) as Toolbar?
Run Code Online (Sandbox Code Playgroud)

?意味着如果findViewByIdreturn null,那么 thisnull将被分配给val toolbar而不是上升kotlin.TypeCastException: null cannot be cast to non-null type android.support.v7.widget.Toolbar异常

完整代码块示例:

 val toolbar = findViewById(R.id.toolbar) as Toolbar? // toolbar now is nullable 

 if(toolbar != null) {
 // kotlin smart cast of toolbar as not nullable value
        setSupportActionBar(toolbar) // setup toolbar
        toolbar.setNavigationIcon(R.drawable.ic_map)

        val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
        val toggle = ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
        drawer.addDrawerListener(toggle) // navigation drawer
        toggle.syncState()
}
Run Code Online (Sandbox Code Playgroud)