class Fragment : Fragment() {
        private lateinit var binding: _FragmentBinding
        private val myViewModel: MainViewModel by activityViewModels()
        override fun onCreateView(
          inflater: LayoutInflater, container: ViewGroup?,
          savedInstanceState: Bundle?
        ): View? {
          binding = _FragmentBinding.inflate(inflater, container, false)
          val view = binding.root
          binding.apply {
            viewModel = myViewModel
            lifecycleOwner = activity
          return view

      Kotlin language logoFragmentPattern

      The Fragment class contains a _FragmentBinding variable that references a _FragmentBinding object obtained from the activity's viewModel. This _FragmentBinding object is used to obtain a reference to the MainViewModel, which is then used to initialize the myViewModel variable. Finally, the code overrides onCreateView() to assign the view obtained from the _FragmentBinding as the view model.


        Add Comment

        Log in to add a comment

        Codiga - All rights reserved 2022.