Home > Blockchain >  New Intent - requireActivity() and requireContext()
New Intent - requireActivity() and requireContext()

Time:12-16

What is the difference between requireActivity() and requireContext() when starting a new Activity Intent

startActivity(Intent(requireContext(), A::class.java))

startActivity(Intent(requireActivity(), B::class.java))

CodePudding user response:

requireActivity() a method that returns the non-null activity instance to fragment or throws an exception. If you are 100% sure that in your fragment's lifecycle, activity is not null

requireContext() returns a nonnull Context , or throws an exception when one isn't available.

CodePudding user response:

A Fragment theoretically can be attached to a Context that is not an Activity. In this case requireActivity() would throw and Exception when requireContext() wouldn't.

You would know if you were using a Fragment in this unconventional way, so for all intents and purposes, there is no practical difference.

requireContext() is returning the same Activity instance as requireActivity() would, but it is upcast to Context. An Activity would be implicitly upcast to Context anyway when you pass it to the Intent constructor, since it is expecting a Context.

  • Related