无法找到导致空异常的问题的原因。由指南进行项目,它没有这个问题。使用与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)
您在
setSupportActionBar(toolbar)
和setContentView
之间缺少navController = ...
关于android - 在NavigationUI上执行命令时发生NullPointerException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56611972/