科特林.TypeCastException:null 不能强制转换为非 null 类型 android.support.



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

另一个原因可能是您将 setContentView 放在导致此异常的项目下方。至少我是这样把它固定在我这边的。

Sanislondra 发现我之所以收到此异常,是因为 xml 中的navigation graphs id应该与底部导航菜单 xml 中menu itemsid相匹配。

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

零安全是内置在部分Kotlin中的重要内容。它可以帮助您在开发的早期阶段揭示大多数 NPE。在官方网站上阅读有关空Kotlin安全的更多信息。

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

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

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

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

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

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

最新更新