[英]kotlin.TypeCastException: null cannot be cast to non-null type android.support.design.widget.FloatingActionButton
[英]kotlin.TypeCastException: null cannot be cast to non-null type 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)
}
另一个原因可能是您将 setContentView 放在导致此异常的项目下方。 至少我是这样把它固定在我身边的。
Sanislondra 发现我收到此异常的原因是 xml 中的navigation graphs id
应该与底部导航菜单 xml 中的menu items
的id
匹配。
您的布局显然没有带有 id R.id.toolbar
工具栏组件,这就是findViewById(...)
返回无法转换为Toolbar
null
的原因。
Null-safety 在Kotlin
很重要。 它可以帮助您在开发的早期阶段揭示大多数 NPE。 在Kotlin
官方网站上阅读更多关于 null 安全的信息。
val toolbar
变量可以为空。在这种情况下,您当前的代码是正确的,请不要更改它。 而是更正您的布局/错误的工具栏 ID 问题。
var toolbar: Toolbar? = null
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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.