Getting the Context inside a Fragment

It is very easy to get the Context inside an Activity:

  • with the getApplicationContext() method
  • using only “this” because the Activity class extends the Context class

But you can’t use any of these two methods inside a Fragment and you have to replace them respectively with:

  • getActivity().getApplicationContext()
  • getActivity()

I often do this replacement when I use code written for an Activity, but that I must use in a Fragment.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.