我添加了一个新的action Navigation.xml:

 <fragment
    android:id="@+id/launcher_home"
    android:name="com.example.android.codelabs.navigation.MainFragment"
    android:label="@string/home"
    tools:layout="@layout/main_fragment">
    <action
        android:id="@+id/go_to_step_one"
        app:destination="@id/flow_step_one" />
</fragment>

调用导航操作时,如果我使用,导航将正常工作:

 view.findViewById<Button>(R.id.navigate_action_bt)?.setOnClickListener(
            Navigation.createNavigateOnClickListener(R.id.go_to_step_one, null)
    )

但当用lambda调用它时,它不起作用:

 view.findViewById<Button>(R.id.navigate_action_bt)?.setOnClickListener {
        Navigation.createNavigateOnClickListener(R.id.go_to_step_one, null)
    }

推荐答案

Well, that's the proper way of working. The method Navigation.createNavigateOnClickListener() returns a View.OnClickListener and according to the docs the proper way of assiging it is by using, even in Kotlin:

button.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.next_fragment, null));

If you using the method inside the lambda, the lambda itself is the click listener so you're returning a click listener inside the click listener, that's why it isn't working. It's like doing this:

button.setOnClickListener {
            View.OnClickListener {
                Toast.makeText(this, "hi", Toast.LENGTH_LONG).show()
            }
        }

你可能感兴趣的是:

 view.findViewById<Button>(R.id.navigate_action_bt)?.setOnClickListener { view ->
   view.findNavController().navigate(R.id.go_to_step_one)
}

它将在单击按钮时执行导航转换.

Kotlin相关问答推荐

Kotlin协程挂起继续线程

Regex(Kotlin)仅匹配句子末尾的句号,而忽略中间的句号,如缩写

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

如何访问方法引用的接收者?

在 Kotlin 中定义基于多态函数的泛型函数

当我通过媒体通知更改音乐时不要更新我的 UI

Kotlin 复制列表中的项目以创建具有相同数据的不同对象的新列表

Kotlin:查找集合中最常见的元素

SpringBoot 2.5.0 对于 Jackson Kotlin 类的支持,请在类路径中添加com.fasterxml.jackson.module: jackson-module-kotlin

如何将超过 2 个 api 调用的结果与 Coroutines Flow 结合起来?

找不到 androidsdk.modules

在 Kotlin 中取最后 n 个元素

Kotlin 创建snackbar

未在IntelliJ IDEA上运行临时文件

在kotlin中,如何模拟封装回调函数?

Kotlin not nullable值可以为null吗?

Java Integer.MAX_VALUE 与 Kotlin Int.MAX_VALUE

如果作为 RxJava Observable 提供,Kotlin 密封类子类需要强制转换为基类

WebFlux 功能:如何检测空 Flux 并返回 404?

将协程更新到 1.2.0 后构建失败:META-INF/atomicfu.kotlin_module