Search code examples
androidkotlinandroid-databindingandroid-viewmodelandroid-viewbinding

Initializing data binding variable in corresponding fragment


I have been working through the Android Basics in Kotlin Course available on developer.android.com and have ran into a problem with Data Binding. The project I am working on doesn't have solution code provided, but I have been modeling my approach off of a previous similar Codelab.

I am attempting to initialize data binding variables declared in layout xml files in the fragments corresponding to each layout but when I attempt to initialize the fragment variable I receive an error: "Classifier 'EntreeMenuFragment' does not have a companion object, and thus must be initialized here". build.Gradle has both dataBinding and viewBinding set to true.

<layout
    ...
    
    <data>
        <variable
            name="viewModel"
            type="com.example.lunchtray.model.OrderViewModel" />

        <variable
            name="EntreeMenuFragment"
            type="com.example.lunchtray.ui.order.EntreeMenuFragment" />
    </data>
   
   ...
</layout>
class EntreeMenuFragment : Fragment() {
    private var _binding: FragmentEntreeMenuBinding? = null
    private val binding get() = _binding!!
    private val sharedViewModel: OrderViewModel by activityViewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.apply {
            lifecycleOwner = viewLifecycleOwner
            viewModel = sharedViewModel
            EntreeMenuFragment = this@EntreeMenuFragment  // ERROR
        }
    }

    ....

Error Description


Solution

  • It was sufficient to remove capitalization on the binding variable in order to avoid the error:

    <variable
                name="entreeMenuFragment"
                type="com.example.lunchtray.ui.order.EntreeMenuFragment" />
    
                entreeMenuFragment = this@EntreeMenuFragment  // fixed