使用导航组件检查用户是否来自 kotlin 中的特定片段

Checking if user is coming from a particular fragment in kotlin with Navigation component

我有两个片段,MeasurementFragment 和 AddMeasurementFragment。用户将首先通过第一个片段并单击一个按钮,然后转到第二个片段,然后填写表单并在按下按钮时返回到第一个片段。然后第二个片段中的文本将显示在第一个片段上。

这是我正在使用的一段代码

private  val args: MeasurementsFragmentArgs by navArgs()
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        /*Initialize Views*/

        addMeasurementFab = binding.clientMeasurementFragmentAddMeasurementFab
        addMeasurementFab.setOnClickListener {
            findNavController().navigate(R.id.addMeasurementFragment)
        }

        if (args != null) {
            binding.measurementsFragmentTestingTextView.text =
                args.dressMeasurementModel.measurementName
            addMeasurementFab = binding.clientMeasurementFragmentAddMeasurementFab
        }
    }

这是我使用该代码得到的错误

2021-06-08 17:45:48.958 6894-6894/com.decagonhq.clads E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.decagonhq.clads, PID: 6894
    java.lang.IllegalStateException: Fragment MeasurementsFragment{b497b26} (7f2ac57b-72b8-4dd0-a3e6-32c78d76e934 tag=f1) has null arguments

请问我如何才能在第一时间检查参数是否为空?

而不是使用委托 属性 by navArgs 你必须手动填充你的参数,就像这样

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    val args = arguments
    if (args != null) {
        val measurementArgs = MeasurementsFragmentArgs.fromBundle(args)
        // parse measurementArgs
    }
    // rest of function follows
}

您可以考虑使用范围限定为 activity 的 ViewModel 来保存您希望在片段之间共享的数据。