首页 > 解决方案 > 使用 Kotlin 导航到不同的活动

问题描述

我想使用导航控制器从一个活动导航到另一个活动。我还没有找到一个例子来说明如何做到这一点。Android 文档指示使用其中之一进行导航:

科特林

* Fragment.findNavController()
* View.findNavController()
* Activity.findNavController(viewId: Int)

爪哇

* NavHostFragment.findNavController(Fragment)
* Navigation.findNavController(Activity, @IdRes int viewId)
* Navigation.findNavController(View)

我正在使用科特林。出于某种奇怪的原因,Google 选择为 Kotlin 和 Java 创建单独的方法。

标签: androidkotlin

解决方案


绝对你需要使用:

findNavController().navigate(R.id.action_loginFragment_to_mainActivity)

就我而言,我必须使用:

val root = inflater.inflate(R.layout.fragment_home, container, false)
val btnUbicacion = root.findViewById<View>(R.id.btn_ubicacion) as Button
btnUbicacion.setOnClickListener{
  activity!!.findNavController(R.id.nav_host_fragment).navigate(R.id.nav_gallery)
}

推荐阅读