将视图绑定与片段一起使用 Android

Using View Binding with Fragments Android

我是 Android 的新手。我正在通过制作应用程序来学习。我对视图与片段的绑定有一点疑问。 从 official documentation 开始,他们正在做这样的事情:

    class FragmentOne : Fragment() {

    private val tagLog = "FragmentOne"

    private var _binding: FragmentOneBinding? = null

    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentOneBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.button.setOnClickListener {
            Toast.makeText(
                requireActivity().applicationContext,
                "Button Clicked",
                Toast.LENGTH_SHORT
            ).show()
        }

        binding.tv.text = "Some Text"
    }

    override fun onDestroyView() {
        _binding = null
        Log.i(tagLog, "onDestroyView()")
        super.onDestroyView()
    }
}

有两个变量_binding 和binding。但是,为什么我们不能只使用一个变量并做这样的事情:

class FragmentOne : Fragment() {

private val tagLog = "FragmentOne"

private var _binding: FragmentOneBinding? = null

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = FragmentOneBinding.inflate(inflater, container, false)
    return _binding?.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    _binding?.button?.setOnClickListener {
        Toast.makeText(
            requireActivity().applicationContext,
            "Button Clicked",
            Toast.LENGTH_SHORT
        ).show()
    }

    _binding?.tv?.text = "Some Text"
}

override fun onDestroyView() {
    _binding = null
    Log.i(tagLog, "onDestroyView()")
    super.onDestroyView()
}
}

我运行这段代码,它工作正常。我用单变量有什么问题吗?

直接使用 _binding 也可以,并且没有任何问题,如果您使用它而不是官方文档推荐的方法。

但官方文档建议使用带有下划线前缀的可空变量及其不带前缀的不可空变量,以提高代码的可读性并避免重复空检查。

在一些链式操作中使用 _binding 看起来像这样 _binding?.first?.second?.third?.fourth?.someOperation(),另一方面使用 binding 模式看起来像 binding.first.second.third.fourth.someOperation()。后一个代码比前一个代码更干净。