【问题标题】:How to use AndroidX Navigation Architecture Component programmatically in Kotlin without using xml?如何在不使用 xml 的情况下在 Kotlin 中以编程方式使用 AndroidX 导航架构组件?
【发布时间】:2019-03-30 20:53:53
【问题描述】:

AndroidX Navigation 的文档目前主要涵盖 xml 的使用。 我想看一个使用 Kotlin 和 Fragments 的编程用法示例(因为我目前不知道其他导航器)。

【问题讨论】:

    标签: android kotlin androidx android-architecture-navigation


    【解决方案1】:

    这是一个简单的示例,说明如何使用带有 KTX 工件的 Fragments 以编程方式使用 AndroidX Navigation:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val container = frameLayout(id = R.id.content) // From Splitties Views DSL. Equivalent to FrameLayout().apply { id = R.id.content }
        setContentView(container)
    
        // Add the NavHostFragment if needed
        if (savedInstanceState == null) supportFragmentManager.transaction(now = true) {
            val fragment = NavHostFragment()
            add(R.id.content, fragment)
            setPrimaryNavigationFragment(fragment)
        }
    
        // Use the Kotlin extension from the -ktx dependencies
        // to find the NavController for the given view ID.
        val navController = findNavController(R.id.content)
    
        // Create the graph using the Kotlin DSL, setting it on the NavController
        navController.graph = navController.createGraph(startDestination = R.id.nav_dest_main) {
            fragment<MainFragment>(R.id.nav_dest_main) {
                label = TODO("Put an actual CharSequence")
            }
            fragment<SomeFragment>(R.id.nav_dest_some_fragment) {
                label = TODO("Put an actual CharSequence")
            }
        }
    }
    

    【讨论】:

    • 是否可以从 Kotlin DSL 生成图表?
    【解决方案2】:

    除了 Louis 示例,请查看官方导航组件指南 - Build a graph programmatically using the Kotlin DSL

    【讨论】:

      猜你喜欢
      • 2019-11-03
      • 1970-01-01
      • 2012-09-24
      • 2012-09-06
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      相关资源
      最近更新 更多