为什么不能将Nav Controller声明为类变量?

时间:2019-07-12 21:30:05

标签: android kotlin

我是android的新手,正在学习一些教程。当前正在实现导航控制器,并重写向上按钮功能。这样做的一部分是将操作栏与Nav控制器链接,并覆盖onSupportNavigateUp()。在执行此操作时,我注意到我们必须按id两次获取Nav控制器,因此我决定创建一个执行此操作的类变量并重新使用该变量。问题是当我这样做时,应用程序在启动时崩溃。我的猜测是这是因为我在扩大视图之前试图获取Nav控制器?

所以我的问题是为什么这样做有效:

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        @Suppress("UNUSED_VARIABLE")
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
        val navController = this.findNavController(R.id.myNavHostFragment)
        NavigationUI.setupActionBarWithNavController(this, navController)
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = this.findNavController(R.id.myNavHostFragment)
        return navController.navigateUp()
    }
}

但这不起作用:

class MainActivity : AppCompatActivity() {

    private val navController = this.findNavController(R.id.myNavHostFragment)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        @Suppress("UNUSED_VARIABLE")
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
        NavigationUI.setupActionBarWithNavController(this, navController)
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp()
    }
}

1 个答案:

答案 0 :(得分:0)

是的,您是在视图膨胀之前将navController分配给null,并将其传递给setupActionBarWithNavController 你可以这样,

class MainActivity : AppCompatActivity() {

    private lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        @Suppress("UNUSED_VARIABLE")
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
        NavigationUI.setupActionBarWithNavController(this, navController)
    navController = this.findNavController(R.id.myNavHostFragment)
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp()
    }
}