ViewBindingPropertyDelegate: IllegalStateException when using viewBinding for onCreateView

Trying to update to 1.5.2+, I find this usage causes a crash due to a new internal check in the library.

    private val binding by viewBinding {
        OnboardingContainerFragmentBinding.inflate(layoutInflater)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View = binding.root
IllegalStateException: Fragment’s view can’t be accessed. Fragment’s view is null.
Maybe you try to access view before onViewCreated() or after onDestroyView().
Add check `if (view != null)` before call ViewBinding

The change is stated in the changelog, but I don’t see anything inherently wrong with the above usage considering the viewBinding lambda is invoked lazily. Do you see a way to keep it (we have many in the project) when upgrading to 1.5.2+?

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 15

Most upvoted comments

Will be fixed in 2.0.0

@kirich1409 I could replicate the problem using the sample app adjusting the way we setup the Fragment view. Instead of referecing the xml, using the Binding generated class

from:

class ProfileFragment : Fragment(R.layout.fragment_profile) {

    private val viewBinding by viewBinding(FragmentProfileBinding::bind,
        onViewDestroyed = { _: FragmentProfileBinding ->
            // reset view
        })

to:

class ProfileFragment : Fragment() {

    private val viewBinding by viewBinding(FragmentProfileBinding::bind,
        onViewDestroyed = { _: FragmentProfileBinding ->
            // reset view
        })

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = viewBinding.root

I understand the issue. Try to reproduce it and fix on weekend

By default the library prevent using viewBinding delegate before onViewCreated() will return the result. That’s why crash happens. It’s expected behaviour. I will think about @gabrielfeo case will work without turning off the check

Another variant is

class ProfileFragment : Fragment() {
    private val viewBinding: ProfileBinding by viewBinding(createMethod = CreateMethod.INFLATE)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = viewBinding.root
}

it will work because ViewBindingPropdetyDelegate will call ViewBinding.inflate method via reflection. It’s slower and not recommended.

Prefer to use

class ProfileFragment : Fragment(R.layout.profile) {
    private val viewBinding: ProfileBinding by viewBinding(ProfileBinding::bind)
}

Please try version 1.5.6