Search code examples
androidkotlinandroid-fragmentsnavigationandroid-viewbinding

Not able to use binding with navcontroller


Here is the code :

class FirstFragment : Fragment() {

    private var _binding: FragmentFirstBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        binding.btnOpen.setOnClickListener {
            Navigation.findNavController(view).navigate(R.id.secondFragment)
        }
        return binding.root
    }

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

At line: Navigation.findNavController(view).navigate(R.id.secondFragment) I'm getting error as Type mismatch required view found view?

My question is why we can't combine navcontroller with view binding?

And is there any resources to learn restrictions of using view binding


Solution

  • Instead of view use binding.root Like this:

    Navigation.findNavController(binding.root).navigate(R.id.secondFragment)
    

    binding.root is reference to root view.