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

我是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 } 

我的片段类

  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) } 

你的布局显然没有ID为R.id.toolbar工具栏组件,这就是为什么findViewById(...)返回null不能转换到Toolbar

Kotlin一部分中建立了Null-safety。 它可以帮助你揭示早期发展阶段的大部分NPE。 在官方Kotlin网站上阅读更多关于null安全的信息。

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

在这种情况下,你现在的代码是正确的,不要改变它。 而是纠正你的布局/错误的工具栏ID问题。

var toolbar: Toolbar? = null var toolbar: Toolbar? = null定义了Toolbar类型的可为空的变量,并且如果活动布局中没有工具栏组件,则不会出现异常, 但是如果您期望确实拥有此组件,则会在稍后获得其他异常,甚至导致程序出现不可预知的行为会令你或应用程序用户感到惊讶

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

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

 val toolbar = findViewById(R.id.toolbar) as Toolbar? 

? 意味着如果findViewById返回null ,那么这个null将被分配给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() }