1

Before asking question I want to say I have read this post

As google document said in: this link

you should use this structure to declare binding object (with both _binding and binding) :

private var _binding: ResultProfileBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

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

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

I want to know, If we can use this structure with one declaration binding instead? does it work the same? If No, why not?

class MyFragment: Fragment(R.layout.my_fragment_layout) {

    private var binding: MyFragmentLayoutBinding? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        binding = MyFragmentLayoutBinding.inflate(inflater, container, false)

        return binding!!.root
    }



    override fun onDestroy() {
        super.onDestroy()

        //to prevent from memory leaks
        binding = null
    }
}
  • First one is just using a nullable backing field for non-null property. That means you won't need to constantly check for nullability or cast `binding` to non-null if it's accessed in valid state. – Pawel Jul 10 '21 at 14:12

1 Answers1

0

This will work fine, but it means you will have to deal with the property being nullable the vast majority of times you access it throughout the class.

In the vast majority of cases !! is a code smell. But in the case of the binding, it is valid to use !! in any code that is called during the view lifecycle. Since this happens in so many places in Fragment code, it is cleaner to create a non-nullable property so there is only one place in your code where you're using !!.

Maybe better than !!, you could put a helpful error message like this:

private var _binding: ResultProfileBinding? = null
private val binding: ResultProfileBinding get() = _binding 
    ?: error("Cannot access binding except between between onCreateView and onDestroyView")

but it might be overkill after you're used to how the lifecycle works.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154