Home > Blockchain >  Using View Binding with Fragments Android
Using View Binding with Fragments Android

Time:09-17

I'm new to Android. I'm learning by making an app. I have a small doubt regarding view binding with fragments. From the official documentation, they are doing something like this:

    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()
    }
}

There are two variables _binding and binding. But, why can't we use only one variable and do something like this:

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()
}
}

I run this code and it is working fine. Is there anything wrong if I use single variable?

CodePudding user response:

Using _binding directly would also work and there is nothing wrong, if you use this instead of what official documentation recommends.

But official documentation recommends using nullable variables with an underscore prefix and its non-nullable counterpart without a prefix for better readability of code and avoiding repeated null checks.

Using _binding in some chained operation would look something like this _binding?.first?.second?.third?.fourth?.someOperation(), on the other hand using binding pattern would be binding.first.second.third.fourth.someOperation(). Latter one is cleaner code than it's former counterpart.

  • Related