findNavController().navigate(direction) 不适用于 View.OnLongClickListener,但适用于 View.OnClickListener

findNavController().navigate(direction) does not work for View.OnLongClickListener, but it works for View.OnClickListener

Android 开发人员 Canary 3.4,kotlin。

发现View.OnLongClickListener给出类型不匹配。 Android 中的新导航图是否未考虑 View.OnLongClickListener?

private fun createOnClickListener(stationId: String): View.OnClickListener
{
    return View.OnClickListener {
        val direction = StationListFragmentDirections.ActionStationListFragmentToStationDetailFragment(stationId)
        it.findNavController().navigate(direction)
    }
}

private fun createOnLongClickListener(stationId: String, kindId: String): View.OnLongClickListener
{
    return View.OnLongClickListener {
        val direction = StationListFragmentDirections.ActionStationListFragmentToUpdatePriceFragment(stationId,kindId)
        it.findNavController().navigate(direction)   // <--- Gives error here
    }
}

以上两个函数的行为应该相同,但较低的 (createOnLongClickListener) 为 'direction' 给出了 'Type mismatch' 错误。

不为 View.OnLongClickListener 添加导航支持吗?

View.OnLongClickListener 需要 return 键入布尔值

示例:

val longClick = View.OnLongClickListener {

        return@OnLongClickListener true
    }

找到答案。如果处理了请求,OnLongClickListener 实际上需要响应:

private fun createOnLongClickListener(stationId: String, kindId: String): View.OnLongClickListener
{
    return View.OnLongClickListener {
        val direction = StationListFragmentDirections.ActionStationListFragmentToUpdatePriceFragment(stationId,kindId)
        it.findNavController().navigate(direction)
        true   // <--- Add true here to confirm it is handled
    }
}

...科特林的奇迹...;)