找不到导致空异常问题的原因。按照指南制作项目,它没有这个问题。使用与 GUIDR 中相同的库版本。
错误信息
Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupWithNavController
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
navController = Navigation.findNavController(this, R.id.nav_host_fragment)
bottom_nav.setupWithNavController(navController)
NavigationUI.setupActionBarWithNavController(this, navController)
}
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp( navController, null)
}
}
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
navController = Navigation.findNavController(this, R.id.nav_host_fragment)
您在setContentView
和navController = ...
之间缺少setSupportActionBar(toolbar)
应用程序主题下的res/values/styles:
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
这似乎是原因。 奇怪,因为在指南中它不会造成任何麻烦。